You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by al...@apache.org on 2016/07/20 17:20:08 UTC

[01/11] brooklyn-server git commit: Adds CleanOrphanedLocationsTest unit test

Repository: brooklyn-server
Updated Branches:
  refs/heads/master 284f110a8 -> f8eb654c7


Adds CleanOrphanedLocationsTest unit test


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

Branch: refs/heads/master
Commit: fa578d5c2a5a0901028dd943864f6792967d91f9
Parents: 8f9d73e
Author: Aled Sage <al...@gmail.com>
Authored: Mon Jul 18 22:46:32 2016 +0100
Committer: Ivana Yovcheva <iv...@gmail.com>
Committed: Tue Jul 19 10:48:30 2016 +0300

----------------------------------------------------------------------
 .../launcher/CleanOrphanedLocationsTest.java    | 241 +++++++++++++++++++
 1 file changed, 241 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/fa578d5c/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
new file mode 100644
index 0000000..ff8515a
--- /dev/null
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
@@ -0,0 +1,241 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.launcher;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.Set;
+
+import org.apache.brooklyn.api.location.Location;
+import org.apache.brooklyn.api.location.LocationSpec;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
+import org.apache.brooklyn.api.policy.PolicySpec;
+import org.apache.brooklyn.api.sensor.EnricherSpec;
+import org.apache.brooklyn.core.config.ConfigKeys;
+import org.apache.brooklyn.core.enricher.AbstractEnricher;
+import org.apache.brooklyn.core.feed.AbstractFeed;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.core.mgmt.rebind.transformer.impl.DeleteOrphanedLocationsTransformer;
+import org.apache.brooklyn.core.policy.AbstractPolicy;
+import org.apache.brooklyn.core.sensor.Sensors;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.commons.lang.builder.EqualsBuilder;
+import org.testng.annotations.Test;
+
+import com.beust.jcommander.internal.Sets;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+
+public class CleanOrphanedLocationsTest extends RebindTestFixtureWithApp {
+
+    @Test
+    public void testDeletesOrphanedLocations() throws Exception {
+        SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        SshMachineLocation loc2 = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        assertTransformDeletes(new Deletions().locations(loc.getId(), loc2.getId()));
+    }
+    
+    @Test
+    public void testDeletesOrphanedLocationThatLinksToReachable() throws Exception {
+        Location referantLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        Location refereeLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure(ConfigKeys.newConfigKey(Object.class, "myconfig"), referantLoc));
+        origApp.addLocations(ImmutableList.of(referantLoc));
+        assertTransformDeletes(new Deletions().locations(refereeLoc.getId()));
+    }
+    
+    @Test
+    public void testDeletesOrphanedSubGraph() throws Exception {
+        Location loc1 = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        Location loc2 = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure(ConfigKeys.newConfigKey(Object.class, "myconfig"), loc1));
+        assertTransformDeletes(new Deletions().locations(loc1.getId(), loc2.getId()));
+    }
+
+    @Test
+    public void testKeepsLocationsReferencedInEntityLocs() throws Exception {
+        SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        SshMachineLocation loc2 = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.addLocations(ImmutableList.of(loc, loc2));
+        assertTransformIsNoop();
+    }
+    
+    @Test
+    public void testKeepsLocationsReferencedInSensor() throws Exception {
+        SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.sensors().set(Sensors.newSensor(Object.class, "mysensor"), loc);
+        assertTransformIsNoop();
+    }
+    
+    @Test
+    public void testKeepsLocationsReferencedInConfig() throws Exception {
+        SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.config().set(ConfigKeys.newConfigKey(Object.class, "myconfig"), loc);
+        assertTransformIsNoop();
+    }
+    
+    @Test
+    public void testKeepsLocationsReferencedInComplexTypeSensor() throws Exception {
+        SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        SshMachineLocation loc2 = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.sensors().set(Sensors.newSensor(Object.class, "mysensor"), ImmutableMap.of("mykey", loc, loc2, "myval"));
+        assertTransformIsNoop();
+    }
+    
+    @Test
+    public void testKeepsParentOfReachableLocation() throws Exception {
+        SshMachineLocation parentLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        SshMachineLocation childLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .parent((parentLoc)));
+        origApp.addLocations(ImmutableList.of(childLoc));
+        assertTransformIsNoop();
+    }
+    
+    @Test
+    public void testKeepsChildrenOfReachableLocation() throws Exception {
+        SshMachineLocation parentLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .parent((parentLoc)));
+        origApp.addLocations(ImmutableList.of(parentLoc));
+        assertTransformIsNoop();
+    }
+    
+    @Test
+    public void testKeepsReferencesOfReachableLocation() throws Exception {
+        Location referantLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        Location refereeLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure(ConfigKeys.newConfigKey(Object.class, "myconfig"), referantLoc));
+        origApp.addLocations(ImmutableList.of(refereeLoc));
+        assertTransformIsNoop();
+    }
+    
+    @Test
+    public void testKeepsLocationsReferencedByEnricher() throws Exception {
+        Location loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.enrichers().add(EnricherSpec.create(MyEnricher.class)
+                .configure(ConfigKeys.newConfigKey(Object.class, "myconfig"), loc));
+        assertTransformIsNoop();
+    }
+    
+    @Test
+    public void testKeepsLocationsReferencedByPolicy() throws Exception {
+        Location loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.policies().add(PolicySpec.create(MyPolicy.class)
+                .configure(ConfigKeys.newConfigKey(Object.class, "myconfig"), loc));
+        assertTransformIsNoop();
+    }
+    
+    @Test
+    public void testKeepsLocationsReferencedByFeed() throws Exception {
+        Location loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        MyFeed feed = new MyFeed();
+        feed.config().set(ConfigKeys.newConfigKey(Object.class, "myconfig"), loc);
+        origApp.feeds().add(feed);
+        assertTransformIsNoop();
+    }
+    
+    private void assertTransformIsNoop() throws Exception {
+        BrooklynMementoRawData origData = getRawData();
+        BrooklynMementoRawData transformedData = transformRawData(origData);
+        assertRawData(transformedData, origData);
+    }
+
+    private void assertTransformDeletes(Deletions deletions) throws Exception {
+        BrooklynMementoRawData origData = getRawData();
+        BrooklynMementoRawData transformedData = transformRawData(origData);
+        assertRawData(transformedData, origData, deletions);
+    }
+
+    protected BrooklynMementoRawData getRawData() throws Exception {
+        RebindTestUtils.waitForPersisted(origApp);
+        return mgmt().getRebindManager().retrieveMementoRawData();
+    }
+
+    protected BrooklynMementoRawData transformRawData(BrooklynMementoRawData rawData) throws Exception {
+        DeleteOrphanedLocationsTransformer transformer = DeleteOrphanedLocationsTransformer.builder().build();
+        return transformer.transform(rawData);
+    }
+
+    protected void assertRawData(BrooklynMementoRawData actual, BrooklynMementoRawData expected) {
+        // asserting lots of times, to ensure we get a more specific error message!
+        assertEquals(actual.getCatalogItems().keySet(), expected.getCatalogItems().keySet());
+        assertEquals(actual.getCatalogItems(), expected.getCatalogItems());
+        assertEquals(actual.getEntities().keySet(), expected.getEntities().keySet());
+        assertEquals(actual.getEntities(), expected.getEntities());
+        assertEquals(actual.getLocations().keySet(), expected.getLocations().keySet());
+        assertEquals(actual.getLocations(), expected.getLocations());
+        assertEquals(actual.getEnrichers().keySet(), expected.getEnrichers().keySet());
+        assertEquals(actual.getEnrichers(), expected.getEnrichers());
+        assertEquals(actual.getPolicies().keySet(), expected.getPolicies().keySet());
+        assertEquals(actual.getPolicies(), expected.getPolicies());
+        assertEquals(actual.getFeeds().keySet(), expected.getFeeds().keySet());
+        assertEquals(actual.getFeeds(), expected.getFeeds());
+        assertTrue(EqualsBuilder.reflectionEquals(actual, expected));
+    }
+    
+    protected void assertRawData(BrooklynMementoRawData actual, BrooklynMementoRawData orig, Deletions deletions) {
+        BrooklynMementoRawData expected = BrooklynMementoRawData.builder()
+                .catalogItems(orig.getCatalogItems())
+                .entities(orig.getEntities())
+                .locations(MutableMap.<String, String>builder().putAll(orig.getLocations()).removeAll(deletions.locations).build())
+                .feeds(MutableMap.<String, String>builder().putAll(orig.getFeeds()).removeAll(deletions.feeds).build())
+                .enrichers(MutableMap.<String, String>builder().putAll(orig.getEnrichers()).removeAll(deletions.enrichers).build())
+                .policies(MutableMap.<String, String>builder().putAll(orig.getPolicies()).removeAll(deletions.policies).build())
+                .build();
+        assertRawData(actual, expected);
+    }
+    
+    @SuppressWarnings("unused")
+    private static class Deletions {
+        final Set<String> locations = Sets.newLinkedHashSet();
+        final Set<String> feeds = Sets.newLinkedHashSet();
+        final Set<String> enrichers = Sets.newLinkedHashSet();
+        final Set<String> policies = Sets.newLinkedHashSet();
+        
+        Deletions locations(String... vals) {
+            if (vals != null) locations.addAll(Arrays.asList(vals));
+            return this;
+        }
+        Deletions feeds(String... vals) {
+            if (vals != null) feeds.addAll(Arrays.asList(vals));
+            return this;
+        }
+        Deletions enrichers(String... vals) {
+            if (vals != null) enrichers.addAll(Arrays.asList(vals));
+            return this;
+        }
+        Deletions policies(String... vals) {
+            if (vals != null) policies.addAll(Arrays.asList(vals));
+            return this;
+        }
+    }
+    
+    public static class MyEnricher extends AbstractEnricher {
+    }
+    
+    public static class MyPolicy extends AbstractPolicy {
+    }
+    
+    public static class MyFeed extends AbstractFeed {
+    }
+}


[02/11] brooklyn-server git commit: Extend XmlUtil#xpath signature

Posted by al...@apache.org.
Extend XmlUtil#xpath signature


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

Branch: refs/heads/master
Commit: c7c8db5d3ca541651d8243aa198b32804844bca3
Parents: fa578d5
Author: Valentin Aitken <bo...@gmail.com>
Authored: Mon Jul 18 20:39:23 2016 +0300
Committer: Ivana Yovcheva <iv...@gmail.com>
Committed: Tue Jul 19 11:05:25 2016 +0300

----------------------------------------------------------------------
 .../org/apache/brooklyn/util/core/xstream/XmlUtil.java    | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/c7c8db5d/core/src/main/java/org/apache/brooklyn/util/core/xstream/XmlUtil.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/util/core/xstream/XmlUtil.java b/core/src/main/java/org/apache/brooklyn/util/core/xstream/XmlUtil.java
index 9f914fa..82b4867 100644
--- a/core/src/main/java/org/apache/brooklyn/util/core/xstream/XmlUtil.java
+++ b/core/src/main/java/org/apache/brooklyn/util/core/xstream/XmlUtil.java
@@ -21,9 +21,11 @@ package org.apache.brooklyn.util.core.xstream;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 
+import javax.xml.namespace.QName;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.xpath.XPathConstants;
 import javax.xml.xpath.XPathExpression;
 import javax.xml.xpath.XPathExpressionException;
 import javax.xml.xpath.XPathFactory;
@@ -56,14 +58,18 @@ public class XmlUtil {
         }
     }
 
-    public static Object xpath(String xml, String xpath) {
+    public static String xpath(String xml, String xpath) {
+        return (String) xpath(xml, xpath, XPathConstants.STRING);
+    }
+
+    public static Object xpath(String xml, String xpath, QName returnType) {
         try {
             DocumentBuilder builder = SharedDocumentBuilder.get();
             Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
             XPathFactory xPathfactory = XPathFactory.newInstance();
             XPathExpression expr = xPathfactory.newXPath().compile(xpath);
             
-            return expr.evaluate(doc);
+            return expr.evaluate(doc, returnType);
             
         } catch (ParserConfigurationException e) {
             throw Exceptions.propagate(e);


[06/11] brooklyn-server git commit: Cleanup code in CleanOrphanedLocationsIntegrationTest

Posted by al...@apache.org.
Cleanup code in CleanOrphanedLocationsIntegrationTest

- update test testCleanedCopiedPersistedState


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

Branch: refs/heads/master
Commit: cdb62f23d11b801329afcc9cd15a6112b61deaf6
Parents: 34afc03
Author: Valentin Aitken <bo...@gmail.com>
Authored: Tue Jul 19 22:43:10 2016 +0300
Committer: Valentin Aitken <bo...@gmail.com>
Committed: Tue Jul 19 22:43:10 2016 +0300

----------------------------------------------------------------------
 .../CleanOrphanedLocationsIntegrationTest.java  | 248 ++++++++++++++++++
 .../CleanOrphanedLocationsLiveTest.java         | 257 -------------------
 2 files changed, 248 insertions(+), 257 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cdb62f23/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsIntegrationTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsIntegrationTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsIntegrationTest.java
new file mode 100644
index 0000000..cb81bde
--- /dev/null
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsIntegrationTest.java
@@ -0,0 +1,248 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.launcher;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
+import org.apache.brooklyn.api.mgmt.rebind.RebindManager;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
+import org.apache.brooklyn.core.mgmt.ha.OsgiManager;
+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.transformer.impl.DeleteOrphanedLocationsTransformer;
+import org.apache.brooklyn.core.server.BrooklynServerConfig;
+import org.apache.brooklyn.core.server.BrooklynServerPaths;
+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.commons.lang.builder.EqualsBuilder;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+
+import java.util.Map;
+import java.util.Set;
+
+public class CleanOrphanedLocationsIntegrationTest {
+
+    private String PERSISTED_STATE_PATH_WITH_ORPHANED_LOCATIONS = "/orphaned-locations-test-data/data-with-orphaned-locations";
+    private String PERSISTED_STATE_PATH_WITH_MULTIPLE_LOCATIONS_OCCURRENCE = "/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests";
+    private String PERSISTED_STATE_PATH_WITHOUT_ORPHANED_LOCATIONS = "/orphaned-locations-test-data/data-without-orphaned-locations";
+    private String PERSISTED_STATE_DESTINATION_PATH = "/orphaned-locations-test-data/copy-persisted-state-destination";
+
+
+    private String persistenceDirWithOrphanedLocations;
+    private String persistenceDirWithoutOrphanedLocations;
+    private String persistenceDirWithMultipleLocationsOccurrence;
+    private String destinationDir;
+    private String persistenceLocation;
+
+    private DeleteOrphanedLocationsTransformer transformer;
+
+    private ManagementContext managementContext;
+
+    @BeforeMethod(alwaysRun = true)
+    public void initialize() throws Exception {
+        persistenceDirWithOrphanedLocations = getClass().getResource(PERSISTED_STATE_PATH_WITH_ORPHANED_LOCATIONS).getFile();
+        persistenceDirWithoutOrphanedLocations = getClass().getResource(PERSISTED_STATE_PATH_WITHOUT_ORPHANED_LOCATIONS).getFile();
+        persistenceDirWithMultipleLocationsOccurrence = getClass().getResource(PERSISTED_STATE_PATH_WITH_MULTIPLE_LOCATIONS_OCCURRENCE).getFile();
+
+        destinationDir = getClass().getResource(PERSISTED_STATE_DESTINATION_PATH).getFile();
+
+        transformer = DeleteOrphanedLocationsTransformer.builder().build();
+    }
+
+    private void initManagementContextAndPersistence(String persistenceDir) {
+
+        BrooklynProperties brooklynProperties = BrooklynProperties.Factory.builderDefault().build();
+        brooklynProperties.put(BrooklynServerConfig.MGMT_BASE_DIR.getName(), "");
+
+        managementContext = new LocalManagementContext(brooklynProperties);
+
+        persistenceDir = BrooklynServerPaths.newMainPersistencePathResolver(brooklynProperties).location(persistenceLocation).dir(persistenceDir).resolve();
+        PersistenceObjectStore objectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(managementContext, persistenceLocation, persistenceDir,
+                PersistMode.AUTO, HighAvailabilityMode.HOT_STANDBY);
+
+        BrooklynMementoPersisterToObjectStore persister = new BrooklynMementoPersisterToObjectStore(
+                objectStore,
+                ((ManagementContextInternal)managementContext).getBrooklynProperties(),
+                managementContext.getCatalogClassLoader());
+
+        RebindManager rebindManager = managementContext.getRebindManager();
+
+        PersistenceExceptionHandler persistenceExceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
+        ((RebindManagerImpl) rebindManager).setPeriodicPersistPeriod(Duration.ONE_SECOND);
+        rebindManager.setPersister(persister, persistenceExceptionHandler);
+    }
+
+    @Test
+    public void testSelectionWithOrphanedLocationsInData() {
+        final Set<String> locationsToKeep = MutableSet.of(
+                "tjdywoxbji",
+                "pudtixbw89"
+        );
+        final Set<String> orphanedLocations = MutableSet.of(
+                "banby1jx4j",
+                "msyp655po0",
+                "ppamsemxgo"
+        );
+
+        initManagementContextAndPersistence(persistenceDirWithOrphanedLocations);
+        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
+
+        Set<String> allReferencedLocationsFoundByTransformer = transformer.findAllReferencedLocations(mementoRawData);
+        Map<String, String> locationsToKeepFoundByTransformer = transformer.findLocationsToKeep(mementoRawData);
+
+        Asserts.assertEquals(allReferencedLocationsFoundByTransformer, locationsToKeep);
+        Asserts.assertEquals(locationsToKeepFoundByTransformer.keySet(), locationsToKeep);
+
+        Map<String, String> locationsNotToKeepDueToTransormer = MutableMap.of();
+        locationsNotToKeepDueToTransormer.putAll(mementoRawData.getLocations());
+        for (Map.Entry location: locationsToKeepFoundByTransformer.entrySet()) {
+            locationsNotToKeepDueToTransormer.remove(location.getKey());
+        }
+        Set<String> notReferencedLocationsDueToTransormer = MutableSet.of();
+        notReferencedLocationsDueToTransormer.addAll(mementoRawData.getLocations().keySet());
+        for (String location: allReferencedLocationsFoundByTransformer) {
+            notReferencedLocationsDueToTransormer.remove(location);
+        }
+
+        Asserts.assertEquals(notReferencedLocationsDueToTransormer, orphanedLocations);
+        Asserts.assertEquals(locationsNotToKeepDueToTransormer.keySet(), orphanedLocations);
+
+
+        BrooklynMementoRawData transformedMemento = transformer.transform(mementoRawData);
+        Asserts.assertFalse(EqualsBuilder.reflectionEquals(mementoRawData, transformedMemento));
+        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData.getEntities(), transformedMemento.getEntities()));
+        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData.getEnrichers(), transformedMemento.getEnrichers()));
+        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData.getPolicies(), transformedMemento.getPolicies()));
+        Asserts.assertFalse(EqualsBuilder.reflectionEquals(mementoRawData.getLocations(), transformedMemento.getLocations()));
+    }
+
+    @Test
+    public void testSelectionWithoutOrphanedLocationsInData() {
+
+        Set<String> locationsToKeep = MutableSet.of(
+                "tjdywoxbji",
+                "pudtixbw89"
+        );
+
+        initManagementContextAndPersistence(persistenceDirWithoutOrphanedLocations);
+        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
+
+        Set<String> allReferencedLocationsFoundByTransformer = transformer.findAllReferencedLocations(mementoRawData);
+        Map<String, String> locationsToKeepFoundByTransformer = transformer.findLocationsToKeep(mementoRawData);
+
+        Asserts.assertEquals(allReferencedLocationsFoundByTransformer, locationsToKeep);
+        Asserts.assertEquals(locationsToKeepFoundByTransformer.keySet(), locationsToKeep);
+
+        Map<String, String> locationsNotToKeepDueToTransormer = MutableMap.of();
+        locationsNotToKeepDueToTransormer.putAll(mementoRawData.getLocations());
+        for (Map.Entry location: locationsToKeepFoundByTransformer.entrySet()) {
+            locationsNotToKeepDueToTransormer.remove(location.getKey());
+        }
+        Set<String> notReferencedLocationsDueToTransormer = MutableSet.of();
+        notReferencedLocationsDueToTransormer.addAll(mementoRawData.getLocations().keySet());
+        for (String location: allReferencedLocationsFoundByTransformer) {
+            notReferencedLocationsDueToTransormer.remove(location);
+        }
+
+        Asserts.assertSize(locationsNotToKeepDueToTransormer.keySet(), 0);
+        Asserts.assertSize(notReferencedLocationsDueToTransormer, 0);
+
+        BrooklynMementoRawData transformedMemento = transformer.transform(mementoRawData);
+        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData, transformedMemento));
+    }
+
+    @Test
+    public void testCleanedCopiedPersistedState() throws Exception {
+
+        BrooklynLauncher launcher = BrooklynLauncher.newInstance()
+                .brooklynProperties(OsgiManager.USE_OSGI, false)
+                .persistMode(PersistMode.AUTO)
+                .persistenceDir(persistenceDirWithOrphanedLocations)
+                .persistenceLocation(persistenceLocation)
+                .highAvailabilityMode(HighAvailabilityMode.DISABLED);
+
+        try {
+            launcher.cleanOrphanedLocations(destinationDir, null);
+        } catch (Exception e) {
+            throw new Exception(e);
+        } finally {
+            launcher.terminate();
+        }
+
+        initManagementContextAndPersistence(destinationDir);
+        BrooklynMementoRawData mementoRawDataFromCleanedState = managementContext.getRebindManager().retrieveMementoRawData();
+        Asserts.assertTrue(mementoRawDataFromCleanedState.getEntities().size() != 0);
+        Asserts.assertTrue(mementoRawDataFromCleanedState.getLocations().size() != 0);
+
+
+        initManagementContextAndPersistence(persistenceDirWithoutOrphanedLocations);
+        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
+
+        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData, mementoRawDataFromCleanedState));
+    }
+
+    @Test
+    public void testMultipleLocationOccurrenceInEntity() {
+        Set<String> allReferencedLocations = MutableSet.of(
+                "m72nvkl799",
+                "m72nTYl799",
+                "m72LKVN799",
+                "jf4rwubqyb",
+                "jf4rwuTTTb",
+                "jf4rwuHHHb",
+                "m72nvkl799",
+                "m72nPTUF99",
+                "m72nhtDr99",
+                "pski1c4s14"
+        );
+
+        Set<String> locationsToKeep = MutableSet.of(
+                "m72nvkl799",
+                "jf4rwubqyb",
+                "pski1c4s14"
+        );
+
+        initManagementContextAndPersistence(persistenceDirWithMultipleLocationsOccurrence);
+
+        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
+        Set<String> allReferencedLocationsFoundByTransformer = transformer.findAllReferencedLocations(mementoRawData);
+        Map<String, String> locationsToKeepFoundByTransformer = transformer.findLocationsToKeep(mementoRawData);
+
+        Asserts.assertEquals(allReferencedLocationsFoundByTransformer, allReferencedLocations);
+        Asserts.assertEquals(locationsToKeepFoundByTransformer.keySet(), locationsToKeep);
+    }
+
+    @AfterMethod
+    public void cleanCopiedPersistedState() {
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/cdb62f23/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsLiveTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsLiveTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsLiveTest.java
deleted file mode 100644
index cda7cc0..0000000
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsLiveTest.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.launcher;
-
-import org.apache.brooklyn.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
-import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
-import org.apache.brooklyn.api.mgmt.rebind.RebindManager;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
-import org.apache.brooklyn.core.mgmt.ha.OsgiManager;
-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.transformer.impl.DeleteOrphanedLocationsTransformer;
-import org.apache.brooklyn.core.server.BrooklynServerConfig;
-import org.apache.brooklyn.core.server.BrooklynServerPaths;
-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.commons.lang.builder.EqualsBuilder;
-import org.testng.annotations.AfterMethod;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-import org.apache.brooklyn.core.internal.BrooklynProperties;
-
-import java.util.Map;
-import java.util.Set;
-
-public class CleanOrphanedLocationsLiveTest {
-
-    private String PERSISTED_STATE_PATH_WITH_ORPHANED_LOCATIONS = "/orphaned-locations-test-data/data-with-orphaned-locations";
-    private String PERSISTED_STATE_PATH_WITH_MULTIPLE_LOCATIONS_OCCURRENCE = "/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests";
-    private String PERSISTED_STATE_PATH_WITHOUT_ORPHANED_LOCATIONS = "/orphaned-locations-test-data/data-without-orphaned-locations";
-    private String PERSISTED_STATE_DESTINATION_PATH = "/orphaned-locations-test-data/copy-persisted-state-destination";
-
-
-    private String persistenceDirWithOrphanedLocations;
-    private String persistenceDirWithoutOrphanedLocations;
-    private String persistenceDirWithMultipleLocationsOccurrence;
-    private String destinationDir;
-    private String destinationLocation;
-    private String localBrooklynProperties;
-    private String persistenceLocation;
-    private String highAvailabilityMode;
-
-    private DeleteOrphanedLocationsTransformer transformer;
-
-    private ManagementContext managementContext;
-
-    @BeforeMethod(alwaysRun = true)
-    public void initialize() throws Exception {
-        persistenceDirWithOrphanedLocations = getClass().getResource(PERSISTED_STATE_PATH_WITH_ORPHANED_LOCATIONS).getFile();
-        persistenceDirWithoutOrphanedLocations = getClass().getResource(PERSISTED_STATE_PATH_WITHOUT_ORPHANED_LOCATIONS).getFile();
-        persistenceDirWithMultipleLocationsOccurrence = getClass().getResource(PERSISTED_STATE_PATH_WITH_MULTIPLE_LOCATIONS_OCCURRENCE).getFile();
-
-        destinationDir = getClass().getResource(PERSISTED_STATE_DESTINATION_PATH).getFile();
-
-        transformer = DeleteOrphanedLocationsTransformer.builder().build();
-    }
-
-    private void initManagementContextAndPersistence(String persistenceDir) {
-
-        BrooklynProperties brooklynProperties = BrooklynProperties.Factory.builderDefault().build();
-        brooklynProperties.put(BrooklynServerConfig.MGMT_BASE_DIR.getName(), "");
-
-        managementContext = new LocalManagementContext(brooklynProperties);
-
-        if (persistenceLocation == null) {
-            persistenceLocation = brooklynProperties.getConfig(BrooklynServerConfig.PERSISTENCE_LOCATION_SPEC);
-        }
-
-        persistenceDir = BrooklynServerPaths.newMainPersistencePathResolver(brooklynProperties).location(persistenceLocation).dir(persistenceDir).resolve();
-        PersistenceObjectStore objectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(managementContext, persistenceLocation, persistenceDir,
-                PersistMode.AUTO, HighAvailabilityMode.HOT_STANDBY);
-
-        BrooklynMementoPersisterToObjectStore persister = new BrooklynMementoPersisterToObjectStore(
-                objectStore,
-                ((ManagementContextInternal)managementContext).getBrooklynProperties(),
-                managementContext.getCatalogClassLoader());
-
-        RebindManager rebindManager = managementContext.getRebindManager();
-
-        PersistenceExceptionHandler persistenceExceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
-        ((RebindManagerImpl) rebindManager).setPeriodicPersistPeriod(Duration.ONE_SECOND);
-        rebindManager.setPersister(persister, persistenceExceptionHandler);
-    }
-
-    @Test
-    public void testSelectionWithOrphanedLocationsInData() {
-
-        Set<String> locationsToKeep = MutableSet.of(
-                "tjdywoxbji",
-                "pudtixbw89"
-        );
-
-        Set<String> orphanedLocations = MutableSet.of(
-                "banby1jx4j",
-                "msyp655po0",
-                "ppamsemxgo"
-        );
-
-        initManagementContextAndPersistence(persistenceDirWithOrphanedLocations);
-        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
-
-        Set<String> allReferencedLocationsFoundByTransformer = transformer.findAllReferencedLocations(mementoRawData);
-        Map<String, String> locationsToKeepFoundByTransformer = transformer.findLocationsToKeep(mementoRawData);
-
-        Asserts.assertEquals(allReferencedLocationsFoundByTransformer, locationsToKeep);
-        Asserts.assertEquals(locationsToKeepFoundByTransformer.keySet(), locationsToKeep);
-
-        Map<String, String> locationsNotToKeepDueToTransormer = MutableMap.of();
-        locationsNotToKeepDueToTransormer.putAll(mementoRawData.getLocations());
-        for (Map.Entry location: locationsToKeepFoundByTransformer.entrySet()) {
-            locationsNotToKeepDueToTransormer.remove(location.getKey());
-        }
-        Set<String> notReferencedLocationsDueToTransormer = MutableSet.of();
-        notReferencedLocationsDueToTransormer.addAll(mementoRawData.getLocations().keySet());
-        for (String location: allReferencedLocationsFoundByTransformer) {
-            notReferencedLocationsDueToTransormer.remove(location);
-        }
-
-        Asserts.assertEquals(notReferencedLocationsDueToTransormer, orphanedLocations);
-        Asserts.assertEquals(locationsNotToKeepDueToTransormer.keySet(), orphanedLocations);
-
-
-        BrooklynMementoRawData transformedMemento = transformer.transform(mementoRawData);
-        Asserts.assertFalse(EqualsBuilder.reflectionEquals(mementoRawData, transformedMemento));
-        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData.getEntities(), transformedMemento.getEntities()));
-        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData.getEnrichers(), transformedMemento.getEnrichers()));
-        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData.getPolicies(), transformedMemento.getPolicies()));
-        Asserts.assertFalse(EqualsBuilder.reflectionEquals(mementoRawData.getLocations(), transformedMemento.getLocations()));
-    }
-
-    @Test
-    public void testSelectionWithoutOrphanedLocationsInData() {
-
-        Set<String> locationsToKeep = MutableSet.of(
-                "tjdywoxbji",
-                "pudtixbw89"
-        );
-
-        initManagementContextAndPersistence(persistenceDirWithoutOrphanedLocations);
-        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
-
-        Set<String> allReferencedLocationsFoundByTransformer = transformer.findAllReferencedLocations(mementoRawData);
-        Map<String, String> locationsToKeepFoundByTransformer = transformer.findLocationsToKeep(mementoRawData);
-
-        Asserts.assertEquals(allReferencedLocationsFoundByTransformer, locationsToKeep);
-        Asserts.assertEquals(locationsToKeepFoundByTransformer.keySet(), locationsToKeep);
-
-        Map<String, String> locationsNotToKeepDueToTransormer = MutableMap.of();
-        locationsNotToKeepDueToTransormer.putAll(mementoRawData.getLocations());
-        for (Map.Entry location: locationsToKeepFoundByTransformer.entrySet()) {
-            locationsNotToKeepDueToTransormer.remove(location.getKey());
-        }
-        Set<String> notReferencedLocationsDueToTransormer = MutableSet.of();
-        notReferencedLocationsDueToTransormer.addAll(mementoRawData.getLocations().keySet());
-        for (String location: allReferencedLocationsFoundByTransformer) {
-            notReferencedLocationsDueToTransormer.remove(location);
-        }
-
-        Asserts.assertSize(locationsNotToKeepDueToTransormer.keySet(), 0);
-        Asserts.assertSize(notReferencedLocationsDueToTransormer, 0);
-
-        BrooklynMementoRawData transformedMemento = transformer.transform(mementoRawData);
-        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData, transformedMemento));
-    }
-
-    @Test
-    public void testCleanedCopiedPersistedState() throws Exception {
-
-        BrooklynLauncher launcher = BrooklynLauncher.newInstance()
-                .localBrooklynPropertiesFile(localBrooklynProperties)
-                .brooklynProperties(OsgiManager.USE_OSGI, false)
-                .persistMode(PersistMode.AUTO)
-                .persistenceDir(persistenceDirWithOrphanedLocations)
-                .persistenceLocation(persistenceLocation)
-                .highAvailabilityMode(HighAvailabilityMode.DISABLED);
-
-        try {
-            launcher.cleanOrphanedLocations(destinationDir, destinationLocation);
-
-        } catch (Exception e) {
-            throw new Exception(e);
-        } finally {
-            launcher.terminate();
-        }
-
-        initManagementContextAndPersistence(destinationDir);
-        BrooklynMementoRawData mementoRawDataFromCleanedState = managementContext.getRebindManager().retrieveMementoRawData();
-        Asserts.assertTrue(mementoRawDataFromCleanedState.getEntities().size() != 0);
-        Asserts.assertTrue(mementoRawDataFromCleanedState.getLocations().size() != 0);
-
-
-        initManagementContextAndPersistence(persistenceDirWithoutOrphanedLocations);
-        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
-
-        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData, mementoRawDataFromCleanedState));
-    }
-
-    @Test
-    public void testMultipleLocationOccurrenceInEntity() {
-        Set<String> allReferencedLocations = MutableSet.of(
-                "m72nvkl799",
-                "m72nTYl799",
-                "m72LKVN799",
-                "jf4rwubqyb",
-                "jf4rwuTTTb",
-                "jf4rwuHHHb",
-                "m72nvkl799",
-                "m72nPTUF99",
-                "m72nhtDr99"
-        );
-
-        Set<String> locationsToKeep = MutableSet.of(
-                "m72nvkl799",
-                "jf4rwubqyb"
-        );
-
-        initManagementContextAndPersistence(persistenceDirWithMultipleLocationsOccurrence);
-
-        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
-        Set<String> allReferencedLocationsFoundByTransformer = transformer.findAllReferencedLocations(mementoRawData);
-        Map<String, String> locationsToKeepFoundByTransformer = transformer.findLocationsToKeep(mementoRawData);
-
-        Asserts.assertEquals(allReferencedLocationsFoundByTransformer, allReferencedLocations);
-        Asserts.assertEquals(locationsToKeepFoundByTransformer.keySet(), locationsToKeep);
-    }
-
-    @AfterMethod
-    public void cleanCopiedPersistedState() {
-
-    }
-}


[04/11] brooklyn-server git commit: Add test resources for orphaned locations

Posted by al...@apache.org.
Add test resources for orphaned locations


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

Branch: refs/heads/master
Commit: 9e6dfc463e79e1749dae1634b72ab23d4d2f6ecb
Parents: 59f8e8b
Author: Ivana Yovcheva <iv...@gmail.com>
Authored: Tue Jul 19 20:35:19 2016 +0300
Committer: Ivana Yovcheva <iv...@gmail.com>
Committed: Tue Jul 19 20:35:19 2016 +0300

----------------------------------------------------------------------
 launcher/pom.xml                                |  9 ++++++
 .../copy-persisted-state-destination/dummy.txt  |  0
 .../entities/xk1z8wlgx2                         | 34 ++++++++++++++++++++
 .../entities/yudk65cb3j                         | 22 +++++++++++++
 .../locations/banby1jx4j                        | 20 ++++++++++++
 .../locations/msyp655po0                        | 18 +++++++++++
 .../locations/ppamsemxgo                        | 11 +++++++
 .../locations/pudtixbw89                        | 11 +++++++
 .../locations/tjdywoxbji                        | 18 +++++++++++
 .../entities/xk1z8wlgx2                         | 34 ++++++++++++++++++++
 .../entities/yudk65cb3j                         | 22 +++++++++++++
 .../locations/pudtixbw89                        | 11 +++++++
 .../locations/tjdywoxbji                        | 18 +++++++++++
 .../entities/exq3hn5eug                         | 19 +++++++++++
 .../entities/ntvotn3iwc                         | 18 +++++++++++
 .../locations/jf4rwubqyb                        |  7 ++++
 .../locations/m72nvkl799                        | 10 ++++++
 .../locations/pski1c4s14                        |  7 ++++
 18 files changed, 289 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/pom.xml
----------------------------------------------------------------------
diff --git a/launcher/pom.xml b/launcher/pom.xml
index 7bf7a11..2a49bb7 100644
--- a/launcher/pom.xml
+++ b/launcher/pom.xml
@@ -272,6 +272,15 @@
                     </execution>
                 </executions>
             </plugin>
+            <plugin>
+                <groupId>org.apache.rat</groupId>
+                <artifactId>apache-rat-plugin</artifactId>
+                <configuration>
+                    <excludes combine.children="append">
+                        <exclude>**/src/test/resources/orphaned-locations-test-data/**</exclude>
+                    </excludes>
+                </configuration>
+            </plugin>
         </plugins>
     </build>
 </project>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/copy-persisted-state-destination/dummy.txt
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/copy-persisted-state-destination/dummy.txt b/launcher/src/test/resources/orphaned-locations-test-data/copy-persisted-state-destination/dummy.txt
new file mode 100644
index 0000000..e69de29

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/entities/xk1z8wlgx2
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/entities/xk1z8wlgx2 b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/entities/xk1z8wlgx2
new file mode 100644
index 0000000..280a045
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/entities/xk1z8wlgx2
@@ -0,0 +1,34 @@
+<entity>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.entity.stock.BasicApplicationImpl</type>
+  <id>xk1z8wlgx2</id>
+  <displayName>element1</displayName>
+  <tags>
+    <org.apache.brooklyn.core.mgmt.BrooklynTags_-NamedStringTag>
+      <kind>yaml_spec</kind>
+      <contents>name: element1
+location:
+  jclouds:aws-ec2:eu-west-1
+services:
+- type: org.apache.brooklyn.entity.software.base.EmptySoftwareProcess</contents>
+    </org.apache.brooklyn.core.mgmt.BrooklynTags_-NamedStringTag>
+  </tags>
+  <children>
+    <string>yudk65cb3j</string>
+  </children>
+  <config>
+    <camp.template.id>S0Odehz7</camp.template.id>
+    <brooklyn.wrapper__app type="boolean">true</brooklyn.wrapper__app>
+  </config>
+  <locations>
+    <string>tjdywoxbji</string>
+  </locations>
+  <attributes>
+    <service.state.expected>
+      <org.apache.brooklyn.core.entity.lifecycle.Lifecycle_-Transition>
+        <state>RUNNING</state>
+        <timestampUtc>1467993426499</timestampUtc>
+      </org.apache.brooklyn.core.entity.lifecycle.Lifecycle_-Transition>
+    </service.state.expected>
+  </attributes>
+</entity>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/entities/yudk65cb3j
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/entities/yudk65cb3j b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/entities/yudk65cb3j
new file mode 100644
index 0000000..072cdb8
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/entities/yudk65cb3j
@@ -0,0 +1,22 @@
+<entity>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.entity.software.base.EmptySoftwareProcessImpl</type>
+  <id>yudk65cb3j</id>
+  <displayName>EmptySoftwareProcess:yudk</displayName>
+  <parent>xk1z8wlgx2</parent>
+  <config>
+    <camp.template.id>fh4wq1FX</camp.template.id>
+    <onbox.base.dir.resolved type="boolean">true</onbox.base.dir.resolved>
+    <install.unique__label>EmptySoftwareProcess</install.unique__label>
+  </config>
+  <locations>
+    <string>pudtixbw89</string>
+  </locations>
+  <attributes>
+    <softwareservice.provisioningLocation>
+      <locationProxy>tjdywoxbji</locationProxy>
+    </softwareservice.provisioningLocation>
+    <host.subnet.hostname>ec2-54-155-107-26.eu-west-1.compute.amazonaws.com</host.subnet.hostname>
+    <service.process.isRunning type="boolean">true</service.process.isRunning>
+  </attributes>
+</entity>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/banby1jx4j
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/banby1jx4j b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/banby1jx4j
new file mode 100644
index 0000000..e45ee62
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/banby1jx4j
@@ -0,0 +1,20 @@
+<location>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.core.location.access.PortForwardManagerImpl</type>
+  <id>banby1jx4j</id>
+  <displayName>localhost</displayName>
+  <locationConfig>
+    <scope>global</scope>
+    <provider>portForwardManager</provider>
+    <name>localhost</name>
+    <spec.final>portForwardManager(scope=global)</spec.final>
+    <spec.original>portForwardManager(scope=global)</spec.original>
+    <brooklyn.object.constructor.portforward.scope>global</brooklyn.object.constructor.portforward.scope>
+    <brooklyn.object.constructor.special>
+      <null/>
+    </brooklyn.object.constructor.special>
+    <tags>
+      <set/>
+    </tags>
+  </locationConfig>
+</location>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/msyp655po0
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/msyp655po0 b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/msyp655po0
new file mode 100644
index 0000000..f876ce3
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/msyp655po0
@@ -0,0 +1,18 @@
+<location>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.location.jclouds.JcloudsLocation</type>
+  <id>msyp655po0</id>
+  <children>
+    <string>ppamsemxgo</string>
+  </children>
+  <locationConfig>
+    <vmInstanceIds>
+      <map>
+        <entry>
+          <locationProxy>ppamsemxgo</locationProxy>
+          <string>eu-west-1/i-cecb8742</string>
+        </entry>
+      </map>
+    </vmInstanceIds>
+  </locationConfig>
+</location>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/ppamsemxgo
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/ppamsemxgo b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/ppamsemxgo
new file mode 100644
index 0000000..aef9dae
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/ppamsemxgo
@@ -0,0 +1,11 @@
+<location>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation</type>
+  <id>ppamsemxgo</id>
+  <parent>msyp655po0</parent>
+  <locationConfig>
+    <jcloudsParent>
+      <locationProxy>msyp655po0</locationProxy>
+    </jcloudsParent>
+  </locationConfig>
+</location>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/pudtixbw89
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/pudtixbw89 b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/pudtixbw89
new file mode 100644
index 0000000..8368d2d
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/pudtixbw89
@@ -0,0 +1,11 @@
+<location>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation</type>
+  <id>pudtixbw89</id>
+  <parent>tjdywoxbji</parent>
+  <locationConfig>
+    <jcloudsParent>
+      <locationProxy>tjdywoxbji</locationProxy>
+    </jcloudsParent>
+  </locationConfig>
+</location>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/tjdywoxbji
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/tjdywoxbji b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/tjdywoxbji
new file mode 100644
index 0000000..8bb9a76
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-with-orphaned-locations/locations/tjdywoxbji
@@ -0,0 +1,18 @@
+<location>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.location.jclouds.JcloudsLocation</type>
+  <id>tjdywoxbji</id>
+  <children>
+    <string>pudtixbw89</string>
+  </children>
+  <locationConfig>
+    <vmInstanceIds>
+      <map>
+        <entry>
+          <locationProxy>pudtixbw89</locationProxy>
+          <string>eu-west-1/i-edcf8361</string>
+        </entry>
+      </map>
+    </vmInstanceIds>
+  </locationConfig>
+</location>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/entities/xk1z8wlgx2
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/entities/xk1z8wlgx2 b/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/entities/xk1z8wlgx2
new file mode 100644
index 0000000..280a045
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/entities/xk1z8wlgx2
@@ -0,0 +1,34 @@
+<entity>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.entity.stock.BasicApplicationImpl</type>
+  <id>xk1z8wlgx2</id>
+  <displayName>element1</displayName>
+  <tags>
+    <org.apache.brooklyn.core.mgmt.BrooklynTags_-NamedStringTag>
+      <kind>yaml_spec</kind>
+      <contents>name: element1
+location:
+  jclouds:aws-ec2:eu-west-1
+services:
+- type: org.apache.brooklyn.entity.software.base.EmptySoftwareProcess</contents>
+    </org.apache.brooklyn.core.mgmt.BrooklynTags_-NamedStringTag>
+  </tags>
+  <children>
+    <string>yudk65cb3j</string>
+  </children>
+  <config>
+    <camp.template.id>S0Odehz7</camp.template.id>
+    <brooklyn.wrapper__app type="boolean">true</brooklyn.wrapper__app>
+  </config>
+  <locations>
+    <string>tjdywoxbji</string>
+  </locations>
+  <attributes>
+    <service.state.expected>
+      <org.apache.brooklyn.core.entity.lifecycle.Lifecycle_-Transition>
+        <state>RUNNING</state>
+        <timestampUtc>1467993426499</timestampUtc>
+      </org.apache.brooklyn.core.entity.lifecycle.Lifecycle_-Transition>
+    </service.state.expected>
+  </attributes>
+</entity>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/entities/yudk65cb3j
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/entities/yudk65cb3j b/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/entities/yudk65cb3j
new file mode 100644
index 0000000..072cdb8
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/entities/yudk65cb3j
@@ -0,0 +1,22 @@
+<entity>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.entity.software.base.EmptySoftwareProcessImpl</type>
+  <id>yudk65cb3j</id>
+  <displayName>EmptySoftwareProcess:yudk</displayName>
+  <parent>xk1z8wlgx2</parent>
+  <config>
+    <camp.template.id>fh4wq1FX</camp.template.id>
+    <onbox.base.dir.resolved type="boolean">true</onbox.base.dir.resolved>
+    <install.unique__label>EmptySoftwareProcess</install.unique__label>
+  </config>
+  <locations>
+    <string>pudtixbw89</string>
+  </locations>
+  <attributes>
+    <softwareservice.provisioningLocation>
+      <locationProxy>tjdywoxbji</locationProxy>
+    </softwareservice.provisioningLocation>
+    <host.subnet.hostname>ec2-54-155-107-26.eu-west-1.compute.amazonaws.com</host.subnet.hostname>
+    <service.process.isRunning type="boolean">true</service.process.isRunning>
+  </attributes>
+</entity>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/locations/pudtixbw89
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/locations/pudtixbw89 b/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/locations/pudtixbw89
new file mode 100644
index 0000000..8368d2d
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/locations/pudtixbw89
@@ -0,0 +1,11 @@
+<location>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.location.jclouds.JcloudsSshMachineLocation</type>
+  <id>pudtixbw89</id>
+  <parent>tjdywoxbji</parent>
+  <locationConfig>
+    <jcloudsParent>
+      <locationProxy>tjdywoxbji</locationProxy>
+    </jcloudsParent>
+  </locationConfig>
+</location>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/locations/tjdywoxbji
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/locations/tjdywoxbji b/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/locations/tjdywoxbji
new file mode 100644
index 0000000..8bb9a76
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/data-without-orphaned-locations/locations/tjdywoxbji
@@ -0,0 +1,18 @@
+<location>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.location.jclouds.JcloudsLocation</type>
+  <id>tjdywoxbji</id>
+  <children>
+    <string>pudtixbw89</string>
+  </children>
+  <locationConfig>
+    <vmInstanceIds>
+      <map>
+        <entry>
+          <locationProxy>pudtixbw89</locationProxy>
+          <string>eu-west-1/i-edcf8361</string>
+        </entry>
+      </map>
+    </vmInstanceIds>
+  </locationConfig>
+</location>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/entities/exq3hn5eug
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/entities/exq3hn5eug b/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/entities/exq3hn5eug
new file mode 100644
index 0000000..e17f3fa
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/entities/exq3hn5eug
@@ -0,0 +1,19 @@
+<entity>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.entity.software.base.EmptyWindowsProcessImpl</type>
+  <id>exq3hn5eug</id>
+  <displayName>EmptyWindowsProcess:exq3</displayName>
+  <parent>ntvotn3iwc</parent>
+  <locations>
+    <string>jf4rwubqyb</string>
+    <string>jf4rwuTTTb</string>
+    <string>jf4rwuHHHb</string>
+  </locations>
+  <attributes>
+    <softwareservice.provisioningLocation>
+      <locationProxy>m72nvkl799</locationProxy>
+      <locationProxy>m72nTYl799</locationProxy>
+      <locationProxy>m72LKVN799</locationProxy>
+    </softwareservice.provisioningLocation>
+  </attributes>
+</entity>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/entities/ntvotn3iwc
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/entities/ntvotn3iwc b/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/entities/ntvotn3iwc
new file mode 100644
index 0000000..fc136ee
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/entities/ntvotn3iwc
@@ -0,0 +1,18 @@
+<entity>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.entity.stock.BasicApplicationImpl</type>
+  <id>ntvotn3iwc</id>
+  <displayName>multipleLocWinLocalhost</displayName>
+  <children>
+    <string>exq3hn5eug</string>
+  </children>
+  <config>
+    <camp.template.id>B6WmUWfk</camp.template.id>
+    <brooklyn.wrapper__app type="boolean">true</brooklyn.wrapper__app>
+  </config>
+  <locations>
+    <string>m72nvkl799</string>
+    <string>m72nPTUF99</string>
+    <string>m72nhtDr99</string>
+  </locations>
+</entity>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/jf4rwubqyb
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/jf4rwubqyb b/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/jf4rwubqyb
new file mode 100644
index 0000000..3380c78
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/jf4rwubqyb
@@ -0,0 +1,7 @@
+<location>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.location.winrm.WinRmMachineLocation</type>
+  <id>jf4rwubqyb</id>
+  <displayName>WinRmMachineLocation:jf4r</displayName>
+  <parent>m72nvkl799</parent>
+</location>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/m72nvkl799
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/m72nvkl799 b/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/m72nvkl799
new file mode 100644
index 0000000..5572f8e
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/m72nvkl799
@@ -0,0 +1,10 @@
+<location>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.location.byon.FixedListMachineProvisioningLocation</type>
+  <id>m72nvkl799</id>
+  <displayName>FixedListMachineProvisioningLocation:m72n</displayName>
+  <children>
+    <string>jf4rwubqyb</string>
+    <string>pski1c4s14</string>
+  </children>
+</location>

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/9e6dfc46/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/pski1c4s14
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/pski1c4s14 b/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/pski1c4s14
new file mode 100644
index 0000000..6d99872
--- /dev/null
+++ b/launcher/src/test/resources/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests/locations/pski1c4s14
@@ -0,0 +1,7 @@
+<location>
+  <brooklynVersion>0.10.0-SNAPSHOT</brooklynVersion>
+  <type>org.apache.brooklyn.location.winrm.WinRmMachineLocation</type>
+  <id>pski1c4s14</id>
+  <displayName>WinRmMachineLocation:pski</displayName>
+  <parent>m72nvkl799</parent>
+</location>


[10/11] brooklyn-server git commit: Fix integration test to use DeleteOrphanedStateTransformer + fix for jenkins + fix flag in MyEnricher

Posted by al...@apache.org.
Fix integration test to use DeleteOrphanedStateTransformer + fix for jenkins + fix flag in MyEnricher


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

Branch: refs/heads/master
Commit: 213fc5ed95bc3dd08175f3fe67c846265ffb0f1d
Parents: 660956f
Author: Ivana Yovcheva <iv...@gmail.com>
Authored: Wed Jul 20 12:25:32 2016 +0300
Committer: Ivana Yovcheva <iv...@gmail.com>
Committed: Wed Jul 20 15:59:15 2016 +0300

----------------------------------------------------------------------
 .../brooklyn/launcher/AbstractCleanOrphanedStateTest.java      | 2 +-
 .../launcher/CleanOrphanedLocationsIntegrationTest.java        | 6 +++---
 .../copy-persisted-state-destination/emptyDirKeeper            | 0
 3 files changed, 4 insertions(+), 4 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/213fc5ed/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractCleanOrphanedStateTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractCleanOrphanedStateTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractCleanOrphanedStateTest.java
index f8d7455..d26c411 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractCleanOrphanedStateTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractCleanOrphanedStateTest.java
@@ -162,7 +162,7 @@ public abstract class AbstractCleanOrphanedStateTest extends RebindTestFixtureWi
     }
     
     public static class MyEnricher extends AbstractEnricher {
-        @SetFromFlag Object obj;
+        @SetFromFlag("myobj") Object obj;
     }
     
     public static class MyPolicy extends AbstractPolicy {

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/213fc5ed/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsIntegrationTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsIntegrationTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsIntegrationTest.java
index cb81bde..e59e526 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsIntegrationTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsIntegrationTest.java
@@ -32,7 +32,7 @@ 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.transformer.impl.DeleteOrphanedLocationsTransformer;
+import org.apache.brooklyn.core.mgmt.rebind.transformer.impl.DeleteOrphanedStateTransformer;
 import org.apache.brooklyn.core.server.BrooklynServerConfig;
 import org.apache.brooklyn.core.server.BrooklynServerPaths;
 import org.apache.brooklyn.test.Asserts;
@@ -63,7 +63,7 @@ public class CleanOrphanedLocationsIntegrationTest {
     private String destinationDir;
     private String persistenceLocation;
 
-    private DeleteOrphanedLocationsTransformer transformer;
+    private DeleteOrphanedStateTransformer transformer;
 
     private ManagementContext managementContext;
 
@@ -75,7 +75,7 @@ public class CleanOrphanedLocationsIntegrationTest {
 
         destinationDir = getClass().getResource(PERSISTED_STATE_DESTINATION_PATH).getFile();
 
-        transformer = DeleteOrphanedLocationsTransformer.builder().build();
+        transformer = DeleteOrphanedStateTransformer.builder().build();
     }
 
     private void initManagementContextAndPersistence(String persistenceDir) {

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/213fc5ed/launcher/src/test/resources/orphaned-locations-test-data/copy-persisted-state-destination/emptyDirKeeper
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/copy-persisted-state-destination/emptyDirKeeper b/launcher/src/test/resources/orphaned-locations-test-data/copy-persisted-state-destination/emptyDirKeeper
new file mode 100644
index 0000000..e69de29


[05/11] brooklyn-server git commit: Fix for keeping location from more references

Posted by al...@apache.org.
Fix for keeping location from more references


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

Branch: refs/heads/master
Commit: 34afc03d6bd7f750c2c3b358e65d9d99c23c3230
Parents: 9e6dfc4
Author: Ivana Yovcheva <iv...@gmail.com>
Authored: Tue Jul 19 21:30:26 2016 +0300
Committer: Ivana Yovcheva <iv...@gmail.com>
Committed: Tue Jul 19 21:30:26 2016 +0300

----------------------------------------------------------------------
 .../DeleteOrphanedLocationsTransformer.java     | 35 +++++++-------------
 1 file changed, 12 insertions(+), 23 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/34afc03d/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
index 1c9cd9e..9f87984 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
@@ -146,25 +146,28 @@ public class DeleteOrphanedLocationsTransformer extends CompoundTransformer impl
     public Set<String> findAllReferencedLocations(BrooklynMementoRawData input) {
         Set<String> allReferencedLocations = MutableSet.of();
 
-        allReferencedLocations.addAll(searchLocationsToKeepInEntities(input.getEntities()));
-        allReferencedLocations.addAll(searchLocationsToKeepInPolicies(input.getPolicies()));
-        allReferencedLocations.addAll(searchLocationsToKeepInEnrichers(input.getEnrichers()));
+        allReferencedLocations.addAll(searchLocationsToKeep(input.getEntities(), "/entity"));
+        allReferencedLocations.addAll(searchLocationsToKeep(input.getPolicies(), "/policy"));
+        allReferencedLocations.addAll(searchLocationsToKeep(input.getEnrichers(), "/enricher"));
+        allReferencedLocations.addAll(searchLocationsToKeep(input.getFeeds(), "/feed"));
         allReferencedLocations.addAll(searchLocationsToKeepInLocations(input.getLocations(), allReferencedLocations));
 
         return allReferencedLocations;
     }
 
-    private Set<String> searchLocationsToKeepInEntities(Map<String, String> entities) {
+    private Set<String> searchLocationsToKeep(Map<String, String> entities, String searchInTypePrefix) {
         Set<String> result = MutableSet.of();
 
         for(Map.Entry entity: entities.entrySet()) {
 
             String prefix = "/entity";
             String location = "/locations/string";
-            String locationProxy = "/attributes/softwareservice.provisioningLocation/locationProxy";
+            String locationProxy = "/attributes//locationProxy";
+            String locationInConfig = "/config//locationProxy";
 
-            result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) entity.getValue(), prefix+location, XPathConstants.NODESET)));
-            result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) entity.getValue(), prefix+locationProxy, XPathConstants.NODESET)));
+            result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) entity.getValue(), searchInTypePrefix+location, XPathConstants.NODESET)));
+            result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) entity.getValue(), searchInTypePrefix+locationProxy, XPathConstants.NODESET)));
+            result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) entity.getValue(), searchInTypePrefix+locationInConfig, XPathConstants.NODESET)));
         }
 
         return result;
@@ -177,14 +180,12 @@ public class DeleteOrphanedLocationsTransformer extends CompoundTransformer impl
         String locationId = "/id";
         String locationChildren = "/children/string";
         String locationParentDirectTag = "/parent";
-        String locationParent = "/locationConfig/jcloudsParent/locationProxy";
-        String locationProxy = "/locationConfig/vmInstanceIds/map/entry/locationProxy";
+        String locationProxy = "/locationConfig//locationProxy";
 
         for (Map.Entry location: locations.entrySet()) {
-            if (alreadyReferencedLocations.contains(location)) {
+            if (alreadyReferencedLocations.contains(location.getKey())) {
                 result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationId, XPathConstants.NODESET)));
                 result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationChildren, XPathConstants.NODESET)));
-                result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationParent, XPathConstants.NODESET)));
                 result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationParentDirectTag, XPathConstants.NODESET)));
                 result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationProxy, XPathConstants.NODESET)));
             }
@@ -193,18 +194,6 @@ public class DeleteOrphanedLocationsTransformer extends CompoundTransformer impl
         return result;
     }
 
-    private Set<String> searchLocationsToKeepInPolicies(Map<String, String> policies) {
-        Set<String> result = MutableSet.of();
-
-        return result;
-    }
-
-    private Set<String> searchLocationsToKeepInEnrichers(Map<String, String> enrichers) {
-        Set<String> result = MutableSet.of();
-
-        return result;
-    }
-
     private Set<String> getAllNodesFromXpath(DTMNodeList nodeList) {
         Set<String> result = MutableSet.of();
 


[08/11] brooklyn-server git commit: XmlUtilTest: add more tests

Posted by al...@apache.org.
XmlUtilTest: add more tests


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

Branch: refs/heads/master
Commit: 5253d4b67827482557bc93a771bdd9f2f5031ba5
Parents: cdb62f2
Author: Aled Sage <al...@gmail.com>
Authored: Tue Jul 19 23:05:42 2016 +0100
Committer: Ivana Yovcheva <iv...@gmail.com>
Committed: Wed Jul 20 12:18:48 2016 +0300

----------------------------------------------------------------------
 .../brooklyn/util/core/xstream/XmlUtilTest.java | 29 ++++++++++++++++++++
 1 file changed, 29 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/5253d4b6/core/src/test/java/org/apache/brooklyn/util/core/xstream/XmlUtilTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/brooklyn/util/core/xstream/XmlUtilTest.java b/core/src/test/java/org/apache/brooklyn/util/core/xstream/XmlUtilTest.java
index 0b195b5..94ff2c8 100644
--- a/core/src/test/java/org/apache/brooklyn/util/core/xstream/XmlUtilTest.java
+++ b/core/src/test/java/org/apache/brooklyn/util/core/xstream/XmlUtilTest.java
@@ -24,14 +24,19 @@ import static org.testng.Assert.assertTrue;
 
 import java.util.List;
 
+import javax.xml.xpath.XPathConstants;
+
 import org.apache.brooklyn.util.core.xstream.XmlUtil.Escaper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.testng.annotations.Test;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
 
 import com.google.common.annotations.Beta;
 import com.google.common.base.Joiner;
 import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 
 public class XmlUtilTest {
@@ -57,6 +62,30 @@ public class XmlUtilTest {
     }
 
     @Test
+    public void testXpathGetsNumber() throws Exception {
+        String xml = "<a><b>1</b></a>";
+        assertEquals(XmlUtil.xpath(xml, "/a/b[text()]", XPathConstants.NUMBER), 1.0D);
+    }
+
+    @Test
+    public void testXpathGetsBoolean() throws Exception {
+        String xml = "<a><b>true</b></a>";
+        assertEquals(XmlUtil.xpath(xml, "/a/b[text()]", XPathConstants.BOOLEAN), Boolean.TRUE);
+    }
+
+    @Test
+    public void testXpathGetsNodeSet() throws Exception {
+        String xml = "<a><b><string>v1</string><string>v2</string></b></a>";
+        NodeList resultSet = (NodeList) XmlUtil.xpath(xml, "/a/b/string", XPathConstants.NODESET);
+        List<String> results = Lists.newArrayList();
+        for (int i = 0; i < resultSet.getLength(); i++) {
+            Node item = resultSet.item(i);
+            results.add(item.getTextContent());
+        }
+        assertEquals(results, ImmutableList.of("v1", "v2"));
+    }
+
+    @Test
     public void testXpathWithEscapedCharsAndXmlVersion1_1() throws Exception {
         StringBuilder xml = new StringBuilder("<?xml version=\"1.1\" encoding=\"UTF-8\"?>"+"\n"+
                 "<a><b>myb</b><c>");


[03/11] brooklyn-server git commit: Cleaner for the old dangling references

Posted by al...@apache.org.
Cleaner for the old dangling references


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

Branch: refs/heads/master
Commit: 59f8e8b44c0399ef270da8b53d4b3e6851069cf4
Parents: c7c8db5
Author: Ivana Yovcheva <iv...@gmail.com>
Authored: Wed Jun 15 19:22:43 2016 +0300
Committer: Ivana Yovcheva <iv...@gmail.com>
Committed: Tue Jul 19 18:30:15 2016 +0300

----------------------------------------------------------------------
 .../DeleteOrphanedLocationsTransformer.java     | 147 ++++++++++-
 .../brooklyn/launcher/common/BasicLauncher.java |   7 +-
 .../CleanOrphanedLocationsLiveTest.java         | 257 +++++++++++++++++++
 .../main/java/org/apache/brooklyn/cli/Main.java |  77 ++++++
 4 files changed, 475 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/59f8e8b4/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
index 985ce37..1c9cd9e 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
@@ -20,13 +20,17 @@ package org.apache.brooklyn.core.mgmt.rebind.transformer.impl;
 
 import java.util.Collection;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
+import com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList;
 import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMemento;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
 import org.apache.brooklyn.api.mgmt.rebind.mementos.EntityMemento;
 import org.apache.brooklyn.api.mgmt.rebind.mementos.LocationMemento;
 import org.apache.brooklyn.core.mgmt.rebind.dto.BrooklynMementoImpl;
 import org.apache.brooklyn.core.mgmt.rebind.transformer.BrooklynMementoTransformer;
+import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
 import org.apache.brooklyn.util.collections.MutableList;
 import org.apache.brooklyn.util.collections.MutableMap;
 import org.apache.brooklyn.util.collections.MutableSet;
@@ -34,17 +38,49 @@ import org.apache.brooklyn.util.collections.MutableSet;
 import com.google.common.annotations.Beta;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
+import org.apache.brooklyn.util.core.xstream.XmlUtil;
+import org.w3c.dom.Node;
+
+import javax.xml.xpath.XPathConstants;
 
 @Beta
-public class DeleteOrphanedLocationsTransformer implements BrooklynMementoTransformer {
+public class DeleteOrphanedLocationsTransformer extends CompoundTransformer implements BrooklynMementoTransformer {
+
+    protected DeleteOrphanedLocationsTransformer(DeleteOrphanedLocationsTransformer.Builder builder) {
+        super(builder);
+    }
+
+    public static Builder builder() {
+        return new DeleteOrphanedLocationsTransformer.Builder();
+    }
+
+    public static class Builder extends CompoundTransformer.Builder {
+
+        public DeleteOrphanedLocationsTransformer build() {
+            return new DeleteOrphanedLocationsTransformer(this);
+        }
+    }
+
+    public BrooklynMementoRawData transform(BrooklynMementoRawData input) {
+        Map<String, String> locationsToKeep = findLocationsToKeep(input);
+
+        return BrooklynMementoRawData.builder()
+                .catalogItems(input.getCatalogItems())
+                .enrichers(input.getEnrichers())
+                .entities(input.getEntities())
+                .feeds(input.getFeeds())
+                .locations(locationsToKeep)
+                .policies(input.getPolicies())
+                .build();
+    }
 
     // TODO Work in progress; untested code!
-    
+
     public BrooklynMemento transform(BrooklynMemento input) throws Exception {
         Set<String> referencedLocationIds = findReferencedLocationIds(input);
         Set<String> unreferencedLocationIds = Sets.newLinkedHashSet();
         List<String> toCheck = Lists.newLinkedList(input.getLocationIds());
-        
+
         while (!toCheck.isEmpty()) {
             String locationId = toCheck.remove(0);
             List<String> locationsInHierarchy = MutableList.<String>builder()
@@ -52,7 +88,7 @@ public class DeleteOrphanedLocationsTransformer implements BrooklynMementoTransf
                     .addAll(findLocationAncestors(input, locationId))
                     .addAll(findLocationDescendents(input, locationId))
                     .build();
-            
+
             if (containsAny(referencedLocationIds, locationsInHierarchy)) {
                 // keep them all
             } else {
@@ -60,7 +96,7 @@ public class DeleteOrphanedLocationsTransformer implements BrooklynMementoTransf
             }
             toCheck.removeAll(locationsInHierarchy);
         }
-        
+
         // TODO What about brooklyn version?
         return BrooklynMementoImpl.builder()
                 .applicationIds(input.getApplicationIds())
@@ -78,26 +114,113 @@ public class DeleteOrphanedLocationsTransformer implements BrooklynMementoTransf
                 .catalogItems(input.getCatalogItemMementos())
                 .build();
     }
-    
+
     public boolean containsAny(Collection<?> container, Iterable<?> contenders) {
         for (Object contender : contenders) {
             if (container.contains(contender)) return true;
         }
         return false;
     }
-    
+
     public Set<String> findReferencedLocationIds(BrooklynMemento input) {
         Set<String> result = Sets.newLinkedHashSet();
-        
+
         for (EntityMemento entity : input.getEntityMementos().values()) {
             result.addAll(entity.getLocations());
         }
         return result;
     }
-    
+
+    public Map<String, String> findLocationsToKeep(BrooklynMementoRawData input) {
+        Map<String, String> locationsToKeep = MutableMap.of();
+        Set<String> allReferencedLocations = findAllReferencedLocations(input);
+
+        for (Map.Entry location: input.getLocations().entrySet()) {
+            if (allReferencedLocations.contains(location.getKey())) {
+                locationsToKeep.put((String) location.getKey(), (String) location.getValue());
+            }
+        }
+        return locationsToKeep;
+    }
+
+    public Set<String> findAllReferencedLocations(BrooklynMementoRawData input) {
+        Set<String> allReferencedLocations = MutableSet.of();
+
+        allReferencedLocations.addAll(searchLocationsToKeepInEntities(input.getEntities()));
+        allReferencedLocations.addAll(searchLocationsToKeepInPolicies(input.getPolicies()));
+        allReferencedLocations.addAll(searchLocationsToKeepInEnrichers(input.getEnrichers()));
+        allReferencedLocations.addAll(searchLocationsToKeepInLocations(input.getLocations(), allReferencedLocations));
+
+        return allReferencedLocations;
+    }
+
+    private Set<String> searchLocationsToKeepInEntities(Map<String, String> entities) {
+        Set<String> result = MutableSet.of();
+
+        for(Map.Entry entity: entities.entrySet()) {
+
+            String prefix = "/entity";
+            String location = "/locations/string";
+            String locationProxy = "/attributes/softwareservice.provisioningLocation/locationProxy";
+
+            result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) entity.getValue(), prefix+location, XPathConstants.NODESET)));
+            result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) entity.getValue(), prefix+locationProxy, XPathConstants.NODESET)));
+        }
+
+        return result;
+    }
+
+    private Set<String> searchLocationsToKeepInLocations(Map<String, String> locations, Set<String> alreadyReferencedLocations) {
+        Set<String> result = MutableSet.of();
+
+        String prefix = "/location";
+        String locationId = "/id";
+        String locationChildren = "/children/string";
+        String locationParentDirectTag = "/parent";
+        String locationParent = "/locationConfig/jcloudsParent/locationProxy";
+        String locationProxy = "/locationConfig/vmInstanceIds/map/entry/locationProxy";
+
+        for (Map.Entry location: locations.entrySet()) {
+            if (alreadyReferencedLocations.contains(location)) {
+                result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationId, XPathConstants.NODESET)));
+                result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationChildren, XPathConstants.NODESET)));
+                result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationParent, XPathConstants.NODESET)));
+                result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationParentDirectTag, XPathConstants.NODESET)));
+                result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationProxy, XPathConstants.NODESET)));
+            }
+        }
+
+        return result;
+    }
+
+    private Set<String> searchLocationsToKeepInPolicies(Map<String, String> policies) {
+        Set<String> result = MutableSet.of();
+
+        return result;
+    }
+
+    private Set<String> searchLocationsToKeepInEnrichers(Map<String, String> enrichers) {
+        Set<String> result = MutableSet.of();
+
+        return result;
+    }
+
+    private Set<String> getAllNodesFromXpath(DTMNodeList nodeList) {
+        Set<String> result = MutableSet.of();
+
+        int i = 0;
+        Node nextNode = nodeList.item(i);
+        while (nextNode != null) {
+            result.add(nextNode.getTextContent());
+            nextNode = nodeList.item(++i);
+        }
+
+        return result;
+    }
+
     public Set<String> findLocationAncestors(BrooklynMemento input, String locationId) {
         Set<String> result = Sets.newLinkedHashSet();
-        
+
         String parentId = null;
         do {
             LocationMemento memento = input.getLocationMemento(locationId);
@@ -107,11 +230,11 @@ public class DeleteOrphanedLocationsTransformer implements BrooklynMementoTransf
 
         return result;
     }
-    
+
     public Set<String> findLocationDescendents(BrooklynMemento input, String locationId) {
         Set<String> result = Sets.newLinkedHashSet();
         List<String> tovisit = Lists.newLinkedList();
-        
+
         tovisit.add(locationId);
         while (!tovisit.isEmpty()) {
             LocationMemento memento = input.getLocationMemento(tovisit.remove(0));

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/59f8e8b4/launcher-common/src/main/java/org/apache/brooklyn/launcher/common/BasicLauncher.java
----------------------------------------------------------------------
diff --git a/launcher-common/src/main/java/org/apache/brooklyn/launcher/common/BasicLauncher.java b/launcher-common/src/main/java/org/apache/brooklyn/launcher/common/BasicLauncher.java
index b550a5b..3c74549 100644
--- a/launcher-common/src/main/java/org/apache/brooklyn/launcher/common/BasicLauncher.java
+++ b/launcher-common/src/main/java/org/apache/brooklyn/launcher/common/BasicLauncher.java
@@ -45,6 +45,7 @@ import org.apache.brooklyn.config.ConfigKey;
 import org.apache.brooklyn.core.catalog.internal.CatalogInitialization;
 import org.apache.brooklyn.core.entity.Entities;
 import org.apache.brooklyn.core.entity.StartableApplication;
+import org.apache.brooklyn.core.entity.factory.ApplicationBuilder;
 import org.apache.brooklyn.core.entity.trait.Startable;
 import org.apache.brooklyn.core.internal.BrooklynProperties;
 import org.apache.brooklyn.core.mgmt.EntityManagementUtils;
@@ -60,6 +61,7 @@ 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.transformer.CompoundTransformer;
+import org.apache.brooklyn.core.mgmt.rebind.transformer.impl.DeleteOrphanedLocationsTransformer;
 import org.apache.brooklyn.core.server.BrooklynServerConfig;
 import org.apache.brooklyn.core.server.BrooklynServerPaths;
 import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
@@ -373,7 +375,6 @@ public class BasicLauncher<T extends BasicLauncher<T>> {
                 managementContext, destinationLocationSpec, destinationDir);
             BrooklynPersistenceUtils.writeMemento(managementContext, memento, destinationObjectStore);
             BrooklynPersistenceUtils.writeManagerMemento(managementContext, planeState, destinationObjectStore);
-
         } catch (Exception e) {
             Exceptions.propagateIfFatal(e);
             LOG.debug("Error copying persisted state (rethrowing): " + e, e);
@@ -382,6 +383,10 @@ public class BasicLauncher<T extends BasicLauncher<T>> {
         }
     }
 
+    public void cleanOrphanedLocations(String destinationDir, @Nullable String destinationLocationSpec) {
+        copyPersistedState(destinationDir, destinationLocationSpec, DeleteOrphanedLocationsTransformer.builder().build());
+    }
+
     /** @deprecated since 0.7.0 use {@link #copyPersistedState} instead */
     // Make private after deprecation
     @Deprecated

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/59f8e8b4/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsLiveTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsLiveTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsLiveTest.java
new file mode 100644
index 0000000..cda7cc0
--- /dev/null
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsLiveTest.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.launcher;
+
+import org.apache.brooklyn.api.mgmt.ManagementContext;
+import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
+import org.apache.brooklyn.api.mgmt.rebind.PersistenceExceptionHandler;
+import org.apache.brooklyn.api.mgmt.rebind.RebindManager;
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
+import org.apache.brooklyn.core.mgmt.ha.OsgiManager;
+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.transformer.impl.DeleteOrphanedLocationsTransformer;
+import org.apache.brooklyn.core.server.BrooklynServerConfig;
+import org.apache.brooklyn.core.server.BrooklynServerPaths;
+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.commons.lang.builder.EqualsBuilder;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+
+import java.util.Map;
+import java.util.Set;
+
+public class CleanOrphanedLocationsLiveTest {
+
+    private String PERSISTED_STATE_PATH_WITH_ORPHANED_LOCATIONS = "/orphaned-locations-test-data/data-with-orphaned-locations";
+    private String PERSISTED_STATE_PATH_WITH_MULTIPLE_LOCATIONS_OCCURRENCE = "/orphaned-locations-test-data/fake-multiple-location-for-multiple-search-tests";
+    private String PERSISTED_STATE_PATH_WITHOUT_ORPHANED_LOCATIONS = "/orphaned-locations-test-data/data-without-orphaned-locations";
+    private String PERSISTED_STATE_DESTINATION_PATH = "/orphaned-locations-test-data/copy-persisted-state-destination";
+
+
+    private String persistenceDirWithOrphanedLocations;
+    private String persistenceDirWithoutOrphanedLocations;
+    private String persistenceDirWithMultipleLocationsOccurrence;
+    private String destinationDir;
+    private String destinationLocation;
+    private String localBrooklynProperties;
+    private String persistenceLocation;
+    private String highAvailabilityMode;
+
+    private DeleteOrphanedLocationsTransformer transformer;
+
+    private ManagementContext managementContext;
+
+    @BeforeMethod(alwaysRun = true)
+    public void initialize() throws Exception {
+        persistenceDirWithOrphanedLocations = getClass().getResource(PERSISTED_STATE_PATH_WITH_ORPHANED_LOCATIONS).getFile();
+        persistenceDirWithoutOrphanedLocations = getClass().getResource(PERSISTED_STATE_PATH_WITHOUT_ORPHANED_LOCATIONS).getFile();
+        persistenceDirWithMultipleLocationsOccurrence = getClass().getResource(PERSISTED_STATE_PATH_WITH_MULTIPLE_LOCATIONS_OCCURRENCE).getFile();
+
+        destinationDir = getClass().getResource(PERSISTED_STATE_DESTINATION_PATH).getFile();
+
+        transformer = DeleteOrphanedLocationsTransformer.builder().build();
+    }
+
+    private void initManagementContextAndPersistence(String persistenceDir) {
+
+        BrooklynProperties brooklynProperties = BrooklynProperties.Factory.builderDefault().build();
+        brooklynProperties.put(BrooklynServerConfig.MGMT_BASE_DIR.getName(), "");
+
+        managementContext = new LocalManagementContext(brooklynProperties);
+
+        if (persistenceLocation == null) {
+            persistenceLocation = brooklynProperties.getConfig(BrooklynServerConfig.PERSISTENCE_LOCATION_SPEC);
+        }
+
+        persistenceDir = BrooklynServerPaths.newMainPersistencePathResolver(brooklynProperties).location(persistenceLocation).dir(persistenceDir).resolve();
+        PersistenceObjectStore objectStore = BrooklynPersistenceUtils.newPersistenceObjectStore(managementContext, persistenceLocation, persistenceDir,
+                PersistMode.AUTO, HighAvailabilityMode.HOT_STANDBY);
+
+        BrooklynMementoPersisterToObjectStore persister = new BrooklynMementoPersisterToObjectStore(
+                objectStore,
+                ((ManagementContextInternal)managementContext).getBrooklynProperties(),
+                managementContext.getCatalogClassLoader());
+
+        RebindManager rebindManager = managementContext.getRebindManager();
+
+        PersistenceExceptionHandler persistenceExceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
+        ((RebindManagerImpl) rebindManager).setPeriodicPersistPeriod(Duration.ONE_SECOND);
+        rebindManager.setPersister(persister, persistenceExceptionHandler);
+    }
+
+    @Test
+    public void testSelectionWithOrphanedLocationsInData() {
+
+        Set<String> locationsToKeep = MutableSet.of(
+                "tjdywoxbji",
+                "pudtixbw89"
+        );
+
+        Set<String> orphanedLocations = MutableSet.of(
+                "banby1jx4j",
+                "msyp655po0",
+                "ppamsemxgo"
+        );
+
+        initManagementContextAndPersistence(persistenceDirWithOrphanedLocations);
+        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
+
+        Set<String> allReferencedLocationsFoundByTransformer = transformer.findAllReferencedLocations(mementoRawData);
+        Map<String, String> locationsToKeepFoundByTransformer = transformer.findLocationsToKeep(mementoRawData);
+
+        Asserts.assertEquals(allReferencedLocationsFoundByTransformer, locationsToKeep);
+        Asserts.assertEquals(locationsToKeepFoundByTransformer.keySet(), locationsToKeep);
+
+        Map<String, String> locationsNotToKeepDueToTransormer = MutableMap.of();
+        locationsNotToKeepDueToTransormer.putAll(mementoRawData.getLocations());
+        for (Map.Entry location: locationsToKeepFoundByTransformer.entrySet()) {
+            locationsNotToKeepDueToTransormer.remove(location.getKey());
+        }
+        Set<String> notReferencedLocationsDueToTransormer = MutableSet.of();
+        notReferencedLocationsDueToTransormer.addAll(mementoRawData.getLocations().keySet());
+        for (String location: allReferencedLocationsFoundByTransformer) {
+            notReferencedLocationsDueToTransormer.remove(location);
+        }
+
+        Asserts.assertEquals(notReferencedLocationsDueToTransormer, orphanedLocations);
+        Asserts.assertEquals(locationsNotToKeepDueToTransormer.keySet(), orphanedLocations);
+
+
+        BrooklynMementoRawData transformedMemento = transformer.transform(mementoRawData);
+        Asserts.assertFalse(EqualsBuilder.reflectionEquals(mementoRawData, transformedMemento));
+        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData.getEntities(), transformedMemento.getEntities()));
+        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData.getEnrichers(), transformedMemento.getEnrichers()));
+        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData.getPolicies(), transformedMemento.getPolicies()));
+        Asserts.assertFalse(EqualsBuilder.reflectionEquals(mementoRawData.getLocations(), transformedMemento.getLocations()));
+    }
+
+    @Test
+    public void testSelectionWithoutOrphanedLocationsInData() {
+
+        Set<String> locationsToKeep = MutableSet.of(
+                "tjdywoxbji",
+                "pudtixbw89"
+        );
+
+        initManagementContextAndPersistence(persistenceDirWithoutOrphanedLocations);
+        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
+
+        Set<String> allReferencedLocationsFoundByTransformer = transformer.findAllReferencedLocations(mementoRawData);
+        Map<String, String> locationsToKeepFoundByTransformer = transformer.findLocationsToKeep(mementoRawData);
+
+        Asserts.assertEquals(allReferencedLocationsFoundByTransformer, locationsToKeep);
+        Asserts.assertEquals(locationsToKeepFoundByTransformer.keySet(), locationsToKeep);
+
+        Map<String, String> locationsNotToKeepDueToTransormer = MutableMap.of();
+        locationsNotToKeepDueToTransormer.putAll(mementoRawData.getLocations());
+        for (Map.Entry location: locationsToKeepFoundByTransformer.entrySet()) {
+            locationsNotToKeepDueToTransormer.remove(location.getKey());
+        }
+        Set<String> notReferencedLocationsDueToTransormer = MutableSet.of();
+        notReferencedLocationsDueToTransormer.addAll(mementoRawData.getLocations().keySet());
+        for (String location: allReferencedLocationsFoundByTransformer) {
+            notReferencedLocationsDueToTransormer.remove(location);
+        }
+
+        Asserts.assertSize(locationsNotToKeepDueToTransormer.keySet(), 0);
+        Asserts.assertSize(notReferencedLocationsDueToTransormer, 0);
+
+        BrooklynMementoRawData transformedMemento = transformer.transform(mementoRawData);
+        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData, transformedMemento));
+    }
+
+    @Test
+    public void testCleanedCopiedPersistedState() throws Exception {
+
+        BrooklynLauncher launcher = BrooklynLauncher.newInstance()
+                .localBrooklynPropertiesFile(localBrooklynProperties)
+                .brooklynProperties(OsgiManager.USE_OSGI, false)
+                .persistMode(PersistMode.AUTO)
+                .persistenceDir(persistenceDirWithOrphanedLocations)
+                .persistenceLocation(persistenceLocation)
+                .highAvailabilityMode(HighAvailabilityMode.DISABLED);
+
+        try {
+            launcher.cleanOrphanedLocations(destinationDir, destinationLocation);
+
+        } catch (Exception e) {
+            throw new Exception(e);
+        } finally {
+            launcher.terminate();
+        }
+
+        initManagementContextAndPersistence(destinationDir);
+        BrooklynMementoRawData mementoRawDataFromCleanedState = managementContext.getRebindManager().retrieveMementoRawData();
+        Asserts.assertTrue(mementoRawDataFromCleanedState.getEntities().size() != 0);
+        Asserts.assertTrue(mementoRawDataFromCleanedState.getLocations().size() != 0);
+
+
+        initManagementContextAndPersistence(persistenceDirWithoutOrphanedLocations);
+        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
+
+        Asserts.assertTrue(EqualsBuilder.reflectionEquals(mementoRawData, mementoRawDataFromCleanedState));
+    }
+
+    @Test
+    public void testMultipleLocationOccurrenceInEntity() {
+        Set<String> allReferencedLocations = MutableSet.of(
+                "m72nvkl799",
+                "m72nTYl799",
+                "m72LKVN799",
+                "jf4rwubqyb",
+                "jf4rwuTTTb",
+                "jf4rwuHHHb",
+                "m72nvkl799",
+                "m72nPTUF99",
+                "m72nhtDr99"
+        );
+
+        Set<String> locationsToKeep = MutableSet.of(
+                "m72nvkl799",
+                "jf4rwubqyb"
+        );
+
+        initManagementContextAndPersistence(persistenceDirWithMultipleLocationsOccurrence);
+
+        BrooklynMementoRawData mementoRawData = managementContext.getRebindManager().retrieveMementoRawData();
+        Set<String> allReferencedLocationsFoundByTransformer = transformer.findAllReferencedLocations(mementoRawData);
+        Map<String, String> locationsToKeepFoundByTransformer = transformer.findLocationsToKeep(mementoRawData);
+
+        Asserts.assertEquals(allReferencedLocationsFoundByTransformer, allReferencedLocations);
+        Asserts.assertEquals(locationsToKeepFoundByTransformer.keySet(), locationsToKeep);
+    }
+
+    @AfterMethod
+    public void cleanCopiedPersistedState() {
+
+    }
+}

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/59f8e8b4/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java
----------------------------------------------------------------------
diff --git a/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java b/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java
index 2d65ad0..53a7829 100644
--- a/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java
+++ b/server-cli/src/main/java/org/apache/brooklyn/cli/Main.java
@@ -827,6 +827,82 @@ public class Main extends AbstractMain {
         }
     }
 
+    @Command(name = "clean-orphaned-locations", description = "Removes existing orphaned locations")
+    public static class CleanOrphanedLocationsCommand extends BrooklynCommandCollectingArgs {
+
+        @Option(name = { "--localBrooklynProperties" }, title = "local brooklyn.properties file",
+                description = "local brooklyn.properties file, specific to this launch (appending to and overriding global properties)")
+        public String localBrooklynProperties;
+
+        @Option(name = { "--persistenceDir" }, title = "persistence dir",
+                description = "The directory to read persisted state (or container name if using an object store)")
+        public String persistenceDir;
+
+        @Option(name = { "--persistenceLocation" }, title = "persistence location",
+                description = "The location spec for an object store to read persisted state")
+        public String persistenceLocation;
+
+        @Option(name = { "--destinationDir" }, required = true, title = "destination dir",
+                description = "The directory to copy persistence data to without orphaned locations")
+        public String destinationDir;
+
+        @Option(name = { "--destinationLocation" }, title = "persistence location",
+                description = "The location spec for an object store to copy data to")
+        public String destinationLocation;
+
+        @Option(name = { "--transformations" }, title = "transformations",
+                description = "local transformations file, to be applied to the copy of the data before uploading it")
+        public String transformations;
+
+        @Override
+        public Void call() throws Exception {
+            checkNotNull(destinationDir, "orphanedReferencesTmpDir");
+
+            BrooklynLauncher launcher;
+            failIfArguments();
+
+            try {
+                log.info("Retrieving and copying persisted state to " + destinationDir + " without orphaned locations");
+
+
+                PersistMode persistMode = PersistMode.AUTO;
+                HighAvailabilityMode highAvailabilityMode = HighAvailabilityMode.DISABLED;
+
+                launcher = BrooklynLauncher.newInstance()
+                        .localBrooklynPropertiesFile(localBrooklynProperties)
+                        .brooklynProperties(OsgiManager.USE_OSGI, false)
+                        .persistMode(persistMode)
+                        .persistenceDir(persistenceDir)
+                        .persistenceLocation(persistenceLocation)
+                        .highAvailabilityMode(highAvailabilityMode);
+
+            } catch (FatalConfigurationRuntimeException e) {
+                throw e;
+            } catch (Exception e) {
+                throw new FatalConfigurationRuntimeException("Fatal error configuring Brooklyn launch: "+e.getMessage(), e);
+            }
+
+            try {
+                launcher.cleanOrphanedLocations(destinationDir, destinationLocation);
+            } catch (FatalRuntimeException e) {
+                throw e;
+            } catch (Exception e) {
+                Exceptions.propagateIfFatal(e);
+                log.error("Error retrieving persisted state: "+Exceptions.collapseText(e), e);
+                Exceptions.propagate(e);
+            } finally {
+                try {
+                    launcher.terminate();
+                } catch (Exception e2) {
+                    log.warn("Subsequent error during termination: "+e2);
+                    log.debug("Details of subsequent error during termination: "+e2, e2);
+                }
+            }
+
+            return null;
+        }
+    }
+
     @Command(name = "copy-state", description = "Retrieves persisted state")
     public static class CopyStateCommand extends BrooklynCommandCollectingArgs {
 
@@ -931,6 +1007,7 @@ public class Main extends AbstractMain {
                         HelpCommand.class,
                         cliInfoCommand(),
                         GeneratePasswordCommand.class,
+                        CleanOrphanedLocationsCommand.class,
                         CopyStateCommand.class,
                         ListAllCommand.class,
                         cliLaunchCommand()


[11/11] brooklyn-server git commit: This closes #264

Posted by al...@apache.org.
This closes #264


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

Branch: refs/heads/master
Commit: f8eb654c79e94437a363e82b1da6938933b9569a
Parents: 284f110 213fc5e
Author: Aled Sage <al...@gmail.com>
Authored: Wed Jul 20 18:19:41 2016 +0100
Committer: Aled Sage <al...@gmail.com>
Committed: Wed Jul 20 18:19:41 2016 +0100

----------------------------------------------------------------------
 .../rebind/mementos/BrooklynMementoRawData.java |  13 +
 .../DeleteOrphanedLocationsTransformer.java     | 125 ----------
 .../impl/DeleteOrphanedStateTransformer.java    | 203 +++++++++++++++
 .../brooklyn/util/core/xstream/XmlUtil.java     |  10 +-
 .../brooklyn/util/core/xstream/XmlUtilTest.java |  29 +++
 .../brooklyn/launcher/common/BasicLauncher.java |   7 +-
 launcher/pom.xml                                |   9 +
 ...stractBrooklynLauncherRebindTestFixture.java | 155 ++++++++++++
 .../AbstractCleanOrphanedStateTest.java         | 179 +++++++++++++
 .../BrooklynLauncherCleanStateTest.java         | 112 +++++++++
 .../BrooklynLauncherRebindTestFixture.java      | 114 +--------
 .../launcher/CleanOrphanedAdjunctsTest.java     |  76 ++++++
 .../CleanOrphanedLocationsIntegrationTest.java  | 248 +++++++++++++++++++
 .../launcher/CleanOrphanedLocationsTest.java    | 219 ++++++++++++++++
 .../emptyDirKeeper                              |   0
 .../entities/xk1z8wlgx2                         |  34 +++
 .../entities/yudk65cb3j                         |  22 ++
 .../locations/banby1jx4j                        |  20 ++
 .../locations/msyp655po0                        |  18 ++
 .../locations/ppamsemxgo                        |  11 +
 .../locations/pudtixbw89                        |  11 +
 .../locations/tjdywoxbji                        |  18 ++
 .../entities/xk1z8wlgx2                         |  34 +++
 .../entities/yudk65cb3j                         |  22 ++
 .../locations/pudtixbw89                        |  11 +
 .../locations/tjdywoxbji                        |  18 ++
 .../entities/exq3hn5eug                         |  19 ++
 .../entities/ntvotn3iwc                         |  18 ++
 .../locations/jf4rwubqyb                        |   7 +
 .../locations/m72nvkl799                        |  10 +
 .../locations/pski1c4s14                        |   7 +
 .../main/java/org/apache/brooklyn/cli/Main.java |  77 ++++++
 32 files changed, 1619 insertions(+), 237 deletions(-)
----------------------------------------------------------------------



[09/11] brooklyn-server git commit: deleting orphaned state: many fixes/tidies

Posted by al...@apache.org.
deleting orphaned state: many fixes/tidies

Now supports deleting enrichers/policies/feeds that have become
orphaned.


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

Branch: refs/heads/master
Commit: 660956f72a860b38db9c81db4cdffde38b3615b2
Parents: 4d0c4b8
Author: Aled Sage <al...@gmail.com>
Authored: Wed Jul 20 09:16:14 2016 +0100
Committer: Ivana Yovcheva <iv...@gmail.com>
Committed: Wed Jul 20 12:18:49 2016 +0300

----------------------------------------------------------------------
 .../rebind/mementos/BrooklynMementoRawData.java |  13 ++
 .../DeleteOrphanedLocationsTransformer.java     | 192 ------------------
 .../impl/DeleteOrphanedStateTransformer.java    | 203 +++++++++++++++++++
 .../brooklyn/launcher/common/BasicLauncher.java |   4 +-
 ...stractBrooklynLauncherRebindTestFixture.java | 155 ++++++++++++++
 .../AbstractCleanOrphanedStateTest.java         | 179 ++++++++++++++++
 .../BrooklynLauncherCleanStateTest.java         | 112 ++++++++++
 .../BrooklynLauncherRebindTestFixture.java      | 114 +----------
 .../launcher/CleanOrphanedAdjunctsTest.java     |  76 +++++++
 .../launcher/CleanOrphanedLocationsTest.java    | 140 ++++---------
 .../copy-persisted-state-destination/dummy.txt  |   0
 11 files changed, 781 insertions(+), 407 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/mementos/BrooklynMementoRawData.java
----------------------------------------------------------------------
diff --git a/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/mementos/BrooklynMementoRawData.java b/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/mementos/BrooklynMementoRawData.java
index 804304d..f2ec4a9 100644
--- a/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/mementos/BrooklynMementoRawData.java
+++ b/api/src/main/java/org/apache/brooklyn/api/mgmt/rebind/mementos/BrooklynMementoRawData.java
@@ -21,6 +21,8 @@ package org.apache.brooklyn.api.mgmt.rebind.mementos;
 import java.util.Collections;
 import java.util.Map;
 
+import javax.annotation.Nullable;
+
 import org.apache.brooklyn.api.objs.BrooklynObjectType;
 
 import com.google.common.annotations.Beta;
@@ -120,6 +122,7 @@ public class BrooklynMementoRawData {
         }
     }
 
+    private final String brooklynVersion;
     private final Map<String, String> entities;
     private final Map<String, String> locations;
     private final Map<String, String> policies;
@@ -128,6 +131,7 @@ public class BrooklynMementoRawData {
     private final Map<String, String> catalogItems;
     
     private BrooklynMementoRawData(Builder builder) {
+        brooklynVersion = builder.brooklynVersion;
         entities = builder.entities;
         locations = builder.locations;
         policies = builder.policies;
@@ -136,6 +140,15 @@ public class BrooklynMementoRawData {
         catalogItems = builder.catalogItems;
     }
 
+    /**
+     * Setting the brooklyn version explicitly is optional. 
+     */
+    @Beta
+    @Nullable
+    public String getBrooklynVersion() {
+        return brooklynVersion;
+    }
+    
     public Map<String, String> getEntities() {
         return Collections.unmodifiableMap(entities);
     }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
deleted file mode 100644
index a26d807..0000000
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.transformer.impl;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.xml.xpath.XPathConstants;
-
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMemento;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.EntityMemento;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.LocationMemento;
-import org.apache.brooklyn.core.mgmt.rebind.transformer.BrooklynMementoTransformer;
-import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.collections.MutableSet;
-import org.apache.brooklyn.util.core.xstream.XmlUtil;
-import org.w3c.dom.Node;
-
-import com.google.common.annotations.Beta;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
-@Beta
-public class DeleteOrphanedLocationsTransformer extends CompoundTransformer implements BrooklynMementoTransformer {
-
-    protected DeleteOrphanedLocationsTransformer(DeleteOrphanedLocationsTransformer.Builder builder) {
-        super(builder);
-    }
-
-    public static Builder builder() {
-        return new DeleteOrphanedLocationsTransformer.Builder();
-    }
-
-    public static class Builder extends CompoundTransformer.Builder {
-
-        @Override
-        public DeleteOrphanedLocationsTransformer build() {
-            return new DeleteOrphanedLocationsTransformer(this);
-        }
-    }
-
-    @Override
-    public BrooklynMementoRawData transform(BrooklynMementoRawData input) {
-        Map<String, String> locationsToKeep = findLocationsToKeep(input);
-
-        return BrooklynMementoRawData.builder()
-                .catalogItems(input.getCatalogItems())
-                .enrichers(input.getEnrichers())
-                .entities(input.getEntities())
-                .feeds(input.getFeeds())
-                .locations(locationsToKeep)
-                .policies(input.getPolicies())
-                .build();
-    }
-
-    @Override
-    public BrooklynMemento transform(BrooklynMemento input) throws Exception {
-        throw new UnsupportedOperationException();
-    }
-
-    protected Set<String> findReferencedLocationIds(BrooklynMemento input) {
-        Set<String> result = Sets.newLinkedHashSet();
-
-        for (EntityMemento entity : input.getEntityMementos().values()) {
-            result.addAll(entity.getLocations());
-        }
-        return result;
-    }
-
-    @VisibleForTesting
-    public Map<String, String> findLocationsToKeep(BrooklynMementoRawData input) {
-        Map<String, String> locationsToKeep = MutableMap.of();
-        Set<String> allReferencedLocations = findAllReferencedLocations(input);
-
-        for (Map.Entry<String, String> location: input.getLocations().entrySet()) {
-            if (allReferencedLocations.contains(location.getKey())) {
-                locationsToKeep.put(location.getKey(), location.getValue());
-            }
-        }
-        return locationsToKeep;
-    }
-
-    @VisibleForTesting
-    public Set<String> findAllReferencedLocations(BrooklynMementoRawData input) {
-        Set<String> allReferencedLocations = MutableSet.of();
-
-        allReferencedLocations.addAll(searchLocationsToKeep(input.getEntities(), "/entity"));
-        allReferencedLocations.addAll(searchLocationsToKeep(input.getPolicies(), "/policy"));
-        allReferencedLocations.addAll(searchLocationsToKeep(input.getEnrichers(), "/enricher"));
-        allReferencedLocations.addAll(searchLocationsToKeep(input.getFeeds(), "/feed"));
-        allReferencedLocations.addAll(searchLocationsToKeepInLocations(input.getLocations(), allReferencedLocations));
-
-        return allReferencedLocations;
-    }
-
-    protected Set<String> searchLocationsToKeep(Map<String, String> entities, String searchInTypePrefix) {
-        Set<String> result = MutableSet.of();
-
-        for(Map.Entry<String, String> entity: entities.entrySet()) {
-
-            String location = "/locations/string";
-            String locationProxy = "//locationProxy";
-
-            result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(entity.getValue(), searchInTypePrefix+location, XPathConstants.NODESET)));
-            result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(entity.getValue(), searchInTypePrefix+locationProxy, XPathConstants.NODESET)));
-        }
-
-        return result;
-    }
-
-    protected Set<String> searchLocationsToKeepInLocations(Map<String, String> locations, Set<String> alreadyReferencedLocations) {
-        Set<String> result = MutableSet.of();
-
-        String prefix = "/location";
-        String locationId = "/id";
-        String locationChildren = "/children/string";
-        String locationParentDirectTag = "/parent";
-        String locationProxy = "//locationProxy";
-
-        for (Map.Entry<String, String> location: locations.entrySet()) {
-            if (alreadyReferencedLocations.contains(location.getKey())) {
-                result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(location.getValue(), prefix+locationId, XPathConstants.NODESET)));
-                result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(location.getValue(), prefix+locationChildren, XPathConstants.NODESET)));
-                result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(location.getValue(), prefix+locationParentDirectTag, XPathConstants.NODESET)));
-                result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(location.getValue(), prefix+locationProxy, XPathConstants.NODESET)));
-            }
-        }
-
-        return result;
-    }
-
-    protected Set<String> getAllNodesFromXpath(org.w3c.dom.NodeList nodeList) {
-        Set<String> result = MutableSet.of();
-
-        int i = 0;
-        Node nextNode = nodeList.item(i);
-        while (nextNode != null) {
-            result.add(nextNode.getTextContent());
-            nextNode = nodeList.item(++i);
-        }
-
-        return result;
-    }
-
-    protected Set<String> findLocationAncestors(BrooklynMemento input, String locationId) {
-        Set<String> result = Sets.newLinkedHashSet();
-
-        String parentId = null;
-        do {
-            LocationMemento memento = input.getLocationMemento(locationId);
-            parentId = memento.getParent();
-            if (parentId != null) result.add(parentId);
-        } while (parentId != null);
-
-        return result;
-    }
-
-    protected Set<String> findLocationDescendents(BrooklynMemento input, String locationId) {
-        Set<String> result = Sets.newLinkedHashSet();
-        List<String> tovisit = Lists.newLinkedList();
-
-        tovisit.add(locationId);
-        while (!tovisit.isEmpty()) {
-            LocationMemento memento = input.getLocationMemento(tovisit.remove(0));
-            List<String> children = memento.getChildren();
-            result.addAll(children);
-            tovisit.addAll(children);
-        };
-
-        return result;
-    }
-}

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedStateTransformer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedStateTransformer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedStateTransformer.java
new file mode 100644
index 0000000..9b76e28
--- /dev/null
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedStateTransformer.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.core.mgmt.rebind.transformer.impl;
+
+import java.util.Map;
+import java.util.Set;
+
+import javax.xml.xpath.XPathConstants;
+
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
+import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.collections.MutableSet;
+import org.apache.brooklyn.util.core.xstream.XmlUtil;
+import org.apache.brooklyn.util.text.Strings;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Node;
+
+import com.google.common.annotations.Beta;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.Sets;
+
+@Beta
+public class DeleteOrphanedStateTransformer extends CompoundTransformer {
+
+    // TODO this isn't really a "CompoundTransformer" - it doesn't register any transformers 
+    // in its builder, but instead overrides {@link #transform(BrooklynMementoRawData)}.
+    // That is a convenient, concise way to get the behaviour we want. But it is a code smell!
+    // We should probably either extract some common super-type, or another interface like
+    // BrooklynMementoRawDataTransformer (but then what would call the latter? Would it be
+    // a CompoundTransformer?!).
+    
+    private static final Logger LOG = LoggerFactory.getLogger(DeleteOrphanedStateTransformer.class);
+
+    public static Builder builder() {
+        return new DeleteOrphanedStateTransformer.Builder();
+    }
+
+    public static class Builder extends CompoundTransformer.Builder {
+        @Override
+        public DeleteOrphanedStateTransformer build() {
+            return new DeleteOrphanedStateTransformer(this);
+        }
+    }
+
+    protected DeleteOrphanedStateTransformer(DeleteOrphanedStateTransformer.Builder builder) {
+        super(builder);
+    }
+
+    @Override
+    public BrooklynMementoRawData transform(BrooklynMementoRawData input) {
+        Map<String, String> locationsToKeep = findLocationsToKeep(input);
+        Map<String, String> enrichersToKeep = copyRetainingKeys(input.getEnrichers(), findAllReferencedEnrichers(input));
+        Map<String, String> policiesToKeep = copyRetainingKeys(input.getPolicies(), findAllReferencedPolicies(input));
+        Map<String, String> feedsToKeep = copyRetainingKeys(input.getFeeds(), findAllReferencedFeeds(input));
+
+        Set<String> locsToDelete = Sets.difference(input.getLocations().keySet(), locationsToKeep.keySet());
+        Set<String> enrichersToDelete = Sets.difference(input.getEnrichers().keySet(), enrichersToKeep.keySet());
+        Set<String> policiesToDelete = Sets.difference(input.getPolicies().keySet(), policiesToKeep.keySet());
+        Set<String> feedsToDelete = Sets.difference(input.getFeeds().keySet(), feedsToKeep.keySet());
+        LOG.info("Deleting {} orphaned location{}: {}", new Object[] {locsToDelete.size(), Strings.s(locsToDelete.size()), locsToDelete});
+        LOG.info("Deleting {} orphaned enricher{}: {}", new Object[] {enrichersToDelete.size(), Strings.s(enrichersToDelete.size()), enrichersToDelete});
+        LOG.info("Deleting {} orphaned polic{}: {}", new Object[] {policiesToDelete.size(), (policiesToDelete.size() == 1 ? "y" : "ies"), policiesToDelete});
+        LOG.info("Deleting {} orphaned feed{}: {}", new Object[] {feedsToDelete.size(), Strings.s(feedsToDelete.size()), feedsToDelete});
+        
+        return BrooklynMementoRawData.builder()
+                .brooklynVersion(input.getBrooklynVersion())
+                .catalogItems(input.getCatalogItems())
+                .entities(input.getEntities())
+                .locations(locationsToKeep)
+                .enrichers(enrichersToKeep)
+                .policies(policiesToKeep)
+                .feeds(feedsToKeep)
+                .build();
+    }
+
+    protected Set<String> findAllReferencedEnrichers(BrooklynMementoRawData input) {
+        return findAllReferencedAdjuncts(input.getEntities(), "entity" + "/enrichers/string");
+    }
+
+    protected Set<String> findAllReferencedPolicies(BrooklynMementoRawData input) {
+        return findAllReferencedAdjuncts(input.getEntities(), "entity" + "/policies/string");
+    }
+
+    protected Set<String> findAllReferencedFeeds(BrooklynMementoRawData input) {
+        return findAllReferencedAdjuncts(input.getEntities(), "entity" + "/feeds/string");
+    }
+
+    protected Set<String> findAllReferencedAdjuncts(Map<String, String> items, String xpath) {
+        Set<String> result = Sets.newLinkedHashSet();
+
+        for(Map.Entry<String, String> entry : items.entrySet()) {
+            result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(entry.getValue(), xpath, XPathConstants.NODESET)));
+        }
+
+        return result;
+    }
+
+    @VisibleForTesting
+    public Map<String, String> findLocationsToKeep(BrooklynMementoRawData input) {
+        Set<String> allReferencedLocations = findAllReferencedLocations(input);
+        return copyRetainingKeys(input.getLocations(), allReferencedLocations);
+    }
+
+    @VisibleForTesting
+    public Set<String> findAllReferencedLocations(BrooklynMementoRawData input) {
+        Set<String> result = Sets.newLinkedHashSet();
+
+        result.addAll(searchLocationsToKeep(input.getEntities(), "/entity"));
+        result.addAll(searchLocationsToKeep(input.getPolicies(), "/policy"));
+        result.addAll(searchLocationsToKeep(input.getEnrichers(), "/enricher"));
+        result.addAll(searchLocationsToKeep(input.getFeeds(), "/feed"));
+        result.addAll(searchLocationsToKeepInLocations(input.getLocations(), result));
+
+        return result;
+    }
+
+    protected Set<String> searchLocationsToKeep(Map<String, String> items, String searchInTypePrefix) {
+        String locationsXpath = searchInTypePrefix+"/locations/string";
+        String locationProxyXpath = searchInTypePrefix+"//locationProxy";
+
+        Set<String> result = Sets.newLinkedHashSet();
+
+        for(Map.Entry<String, String> entry : items.entrySet()) {
+            result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(entry.getValue(), locationsXpath, XPathConstants.NODESET)));
+            result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(entry.getValue(), locationProxyXpath, XPathConstants.NODESET)));
+        }
+
+        return result;
+    }
+
+    protected Set<String> searchLocationsToKeepInLocations(Map<String, String> locations, Set<String> alreadyReferencedLocations) {
+        Set<String> result = Sets.newLinkedHashSet();
+
+        String prefix = "/location";
+        String locationChildrenXpath = prefix+"/children/string";
+        String locationParentDirectTagXpath = prefix+"/parent";
+        String locationProxyXpath = prefix+"//locationProxy";
+
+        Set<String> locsToInspect = alreadyReferencedLocations;
+        
+        while (locsToInspect.size() > 0) {
+            Set<String> referencedLocs = Sets.newLinkedHashSet();
+            for (String id : locsToInspect) {
+                String xmlData = locations.get(id);
+                if (xmlData != null) {
+                    referencedLocs.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(xmlData, locationChildrenXpath, XPathConstants.NODESET)));
+                    referencedLocs.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(xmlData, locationParentDirectTagXpath, XPathConstants.NODESET)));
+                    referencedLocs.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(xmlData, locationProxyXpath, XPathConstants.NODESET)));
+                }
+            }
+            Set<String> newlyDiscoveredLocs = MutableSet.<String>builder()
+                    .addAll(referencedLocs)
+                    .removeAll(alreadyReferencedLocations)
+                    .removeAll(result)
+                    .build();
+            result.addAll(newlyDiscoveredLocs);
+            locsToInspect = newlyDiscoveredLocs;
+        }
+
+        return result;
+    }
+
+    protected <K, V> Map<K, V> copyRetainingKeys(Map<K, V> orig, Set<? extends K> keysToKeep) {
+        Map<K, V> result = MutableMap.of();
+        for (Map.Entry<K, V> entry : orig.entrySet()) {
+            if (keysToKeep.contains(entry.getKey())) {
+                result.put(entry.getKey(), entry.getValue());
+            }
+        }
+        return result;
+    }
+
+    protected Set<String> getAllNodesFromXpath(org.w3c.dom.NodeList nodeList) {
+        Set<String> result = Sets.newLinkedHashSet();
+
+        for (int i = 0; i < nodeList.getLength(); i++) {
+            Node nextNode = nodeList.item(i);
+            if (nextNode != null) {
+                result.add(nextNode.getTextContent());
+            }
+        }
+        
+        return result;
+    }
+}

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/launcher-common/src/main/java/org/apache/brooklyn/launcher/common/BasicLauncher.java
----------------------------------------------------------------------
diff --git a/launcher-common/src/main/java/org/apache/brooklyn/launcher/common/BasicLauncher.java b/launcher-common/src/main/java/org/apache/brooklyn/launcher/common/BasicLauncher.java
index 3c74549..e328d61 100644
--- a/launcher-common/src/main/java/org/apache/brooklyn/launcher/common/BasicLauncher.java
+++ b/launcher-common/src/main/java/org/apache/brooklyn/launcher/common/BasicLauncher.java
@@ -61,7 +61,7 @@ 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.transformer.CompoundTransformer;
-import org.apache.brooklyn.core.mgmt.rebind.transformer.impl.DeleteOrphanedLocationsTransformer;
+import org.apache.brooklyn.core.mgmt.rebind.transformer.impl.DeleteOrphanedStateTransformer;
 import org.apache.brooklyn.core.server.BrooklynServerConfig;
 import org.apache.brooklyn.core.server.BrooklynServerPaths;
 import org.apache.brooklyn.entity.brooklynnode.BrooklynNode;
@@ -384,7 +384,7 @@ public class BasicLauncher<T extends BasicLauncher<T>> {
     }
 
     public void cleanOrphanedLocations(String destinationDir, @Nullable String destinationLocationSpec) {
-        copyPersistedState(destinationDir, destinationLocationSpec, DeleteOrphanedLocationsTransformer.builder().build());
+        copyPersistedState(destinationDir, destinationLocationSpec, DeleteOrphanedStateTransformer.builder().build());
     }
 
     /** @deprecated since 0.7.0 use {@link #copyPersistedState} instead */

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTestFixture.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTestFixture.java b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTestFixture.java
new file mode 100644
index 0000000..f768d81
--- /dev/null
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractBrooklynLauncherRebindTestFixture.java
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.brooklyn.launcher;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+
+import java.util.List;
+
+import org.apache.brooklyn.api.entity.Application;
+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.entity.StartableApplication;
+import org.apache.brooklyn.core.internal.BrooklynProperties;
+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.test.entity.LocalManagementContextForTests;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.test.Asserts;
+import org.apache.brooklyn.util.collections.MutableList;
+import org.apache.brooklyn.util.exceptions.FatalConfigurationRuntimeException;
+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 com.google.common.base.Function;
+import com.google.common.base.Predicates;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+
+public abstract class AbstractBrooklynLauncherRebindTestFixture {
+
+    @SuppressWarnings("unused")
+    private static final Logger log = LoggerFactory.getLogger(AbstractBrooklynLauncherRebindTestFixture.class);
+    
+    protected String persistenceDir;
+    protected String persistenceLocationSpec;
+    protected List<BrooklynLauncher> launchers = MutableList.of();
+    
+    protected abstract String newTempPersistenceContainerName();
+
+    @BeforeMethod(alwaysRun=true)
+    public void setUp() throws Exception {
+        persistenceDir = newTempPersistenceContainerName();
+    }
+    
+    @AfterMethod(alwaysRun=true)
+    public void tearDown() throws Exception {
+        for (BrooklynLauncher l: launchers) {
+            if (l.isStarted()) {
+                l.terminate();
+                PersistenceObjectStore store = getPersistenceStore(l.getServerDetails().getManagementContext());
+                if (store!=null) store.deleteCompletely();
+            }
+        }
+    }
+
+    protected BrooklynLauncher newLauncherBase() {
+        BrooklynLauncher l = BrooklynLauncher.newInstance()
+            .webconsole(false);
+        launchers.add(l);
+        return l;
+    }
+    
+    protected BrooklynLauncher newLauncherDefault(PersistMode mode) {
+        return newLauncherBase()
+                .managementContext(newManagementContextForTests(null))
+                .persistMode(mode)
+                .persistenceDir(persistenceDir)
+                .persistPeriod(Duration.millis(10));
+    }
+    
+    protected LocalManagementContextForTests newManagementContextForTests(BrooklynProperties props) {
+        if (props==null)
+            return new LocalManagementContextForTests();
+        else
+            return new LocalManagementContextForTests(props);
+    }
+
+    protected ManagementContext lastMgmt() {
+        return Iterables.getLast(launchers).getServerDetails().getManagementContext();
+    }
+    
+    protected void runRebindFails(PersistMode persistMode, String dir, String errmsg) throws Exception {
+        try {
+            newLauncherDefault(persistMode)
+                    .persistenceDir(dir)
+                    .start();
+        } catch (FatalConfigurationRuntimeException e) {
+            if (!e.toString().contains(errmsg)) {
+                throw e;
+            }
+        }
+    }
+
+    protected void populatePersistenceDir(String dir, EntitySpec<? extends StartableApplication> appSpec) throws Exception {
+        BrooklynLauncher launcher = newLauncherDefault(PersistMode.CLEAN)
+                .highAvailabilityMode(HighAvailabilityMode.MASTER)
+                .persistenceDir(dir)
+                .application(appSpec)
+                .start();
+        launcher.terminate();
+        assertMementoContainerNonEmptyForTypeEventually("entities");
+    }
+    
+    protected void populatePersistenceDir(String dir, Function<ManagementContext, Void> populator) throws Exception {
+        BrooklynLauncher launcher = newLauncherDefault(PersistMode.CLEAN)
+                .highAvailabilityMode(HighAvailabilityMode.MASTER)
+                .persistenceDir(dir)
+                .start();
+        populator.apply(launcher.getManagementContext());
+        launcher.terminate();
+        assertMementoContainerNonEmptyForTypeEventually("entities");
+    }
+    
+    protected void assertOnlyApp(ManagementContext managementContext, Class<? extends Application> expectedType) {
+        assertEquals(managementContext.getApplications().size(), 1, "apps="+managementContext.getApplications());
+        assertNotNull(Iterables.find(managementContext.getApplications(), Predicates.instanceOf(TestApplication.class), null), "apps="+managementContext.getApplications());
+    }
+    
+    protected void assertMementoContainerNonEmptyForTypeEventually(final String type) {
+        Asserts.succeedsEventually(ImmutableMap.of("timeout", Duration.TEN_SECONDS), new Runnable() {
+            @Override public void run() {
+                getPersistenceStore(lastMgmt()).listContentsWithSubPath(type);
+            }});
+    }
+
+    static PersistenceObjectStore getPersistenceStore(ManagementContext managementContext) {
+        if (managementContext==null) return null;
+        BrooklynMementoPersisterToObjectStore persister = (BrooklynMementoPersisterToObjectStore)managementContext.getRebindManager().getPersister();
+        if (persister==null) return null;
+        return persister.getObjectStore();
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractCleanOrphanedStateTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractCleanOrphanedStateTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractCleanOrphanedStateTest.java
new file mode 100644
index 0000000..f8d7455
--- /dev/null
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/AbstractCleanOrphanedStateTest.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.launcher;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.util.Arrays;
+import java.util.Set;
+
+import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
+import org.apache.brooklyn.core.enricher.AbstractEnricher;
+import org.apache.brooklyn.core.feed.AbstractFeed;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
+import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
+import org.apache.brooklyn.core.mgmt.rebind.transformer.impl.DeleteOrphanedStateTransformer;
+import org.apache.brooklyn.core.policy.AbstractPolicy;
+import org.apache.brooklyn.core.test.entity.TestEntityImpl;
+import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
+import org.apache.commons.lang.builder.EqualsBuilder;
+
+import com.beust.jcommander.internal.Sets;
+import com.google.common.base.Function;
+import com.google.common.base.Functions;
+
+public abstract class AbstractCleanOrphanedStateTest extends RebindTestFixtureWithApp {
+    
+    public static class MementoTweaker implements Function<BrooklynMementoRawData, BrooklynMementoRawData> {
+        private Deletions deletions;
+        
+        public MementoTweaker(Deletions deletions) {
+            this.deletions = deletions;
+        }
+        @Override
+        public BrooklynMementoRawData apply(BrooklynMementoRawData input) {
+            return BrooklynMementoRawData.builder()
+                    .brooklynVersion(input.getBrooklynVersion())
+                    .catalogItems(input.getCatalogItems())
+                    .entities(MutableMap.<String, String>builder().putAll(input.getEntities()).removeAll(deletions.entities).build())
+                    .locations(MutableMap.<String, String>builder().putAll(input.getLocations()).removeAll(deletions.locations).build())
+                    .feeds(MutableMap.<String, String>builder().putAll(input.getFeeds()).removeAll(deletions.feeds).build())
+                    .enrichers(MutableMap.<String, String>builder().putAll(input.getEnrichers()).removeAll(deletions.enrichers).build())
+                    .policies(MutableMap.<String, String>builder().putAll(input.getPolicies()).removeAll(deletions.policies).build())
+                    .build();
+
+        }
+    }
+
+    protected void assertTransformIsNoop() throws Exception {
+        assertTransformIsNoop(getRawData());
+    }
+
+    protected void assertTransformIsNoop(BrooklynMementoRawData origData) throws Exception {
+        assertTransformIsNoop(origData, Functions.<BrooklynMementoRawData>identity());
+    }
+
+    protected void assertTransformIsNoop(Function<? super BrooklynMementoRawData, ? extends BrooklynMementoRawData> origDataTweaker) throws Exception {
+        assertTransformIsNoop(getRawData(), origDataTweaker);
+    }
+    
+    protected void assertTransformIsNoop(BrooklynMementoRawData origData, Function<? super BrooklynMementoRawData, ? extends BrooklynMementoRawData> origDataTweaker) throws Exception {
+        BrooklynMementoRawData origDataTweaked = origDataTweaker.apply(origData);
+        BrooklynMementoRawData transformedData = transformRawData(origDataTweaked);
+        assertRawData(transformedData, origDataTweaked);
+    }
+    
+    protected void assertTransformDeletes(Deletions deletions) throws Exception {
+        assertTransformDeletes(deletions, Functions.<BrooklynMementoRawData>identity());
+    }
+
+    protected void assertTransformDeletes(Deletions deletions, Function<? super BrooklynMementoRawData, ? extends BrooklynMementoRawData> origDataTweaker) throws Exception {
+        BrooklynMementoRawData origData = getRawData();
+        BrooklynMementoRawData origDataTweaked = origDataTweaker.apply(origData);
+        BrooklynMementoRawData transformedData = transformRawData(origDataTweaked);
+        assertRawData(transformedData, origDataTweaked, deletions);
+    }
+
+    protected BrooklynMementoRawData getRawData() throws Exception {
+        RebindTestUtils.waitForPersisted(origApp);
+        return mgmt().getRebindManager().retrieveMementoRawData();
+    }
+
+    protected BrooklynMementoRawData transformRawData(BrooklynMementoRawData rawData) throws Exception {
+        DeleteOrphanedStateTransformer transformer = DeleteOrphanedStateTransformer.builder().build();
+        return transformer.transform(rawData);
+    }
+
+    protected void assertRawData(BrooklynMementoRawData actual, BrooklynMementoRawData expected) {
+        // asserting lots of times, to ensure we get a more specific error message!
+        assertEquals(actual.getCatalogItems().keySet(), expected.getCatalogItems().keySet(), "catalog ids differ");
+        assertEquals(actual.getCatalogItems(), expected.getCatalogItems());
+        assertEquals(actual.getEntities().keySet(), expected.getEntities().keySet(), "entity ids differ");
+        assertEquals(actual.getEntities(), expected.getEntities());
+        assertEquals(actual.getLocations().keySet(), expected.getLocations().keySet(), "location ids differ");
+        assertEquals(actual.getLocations(), expected.getLocations());
+        assertEquals(actual.getEnrichers().keySet(), expected.getEnrichers().keySet(), "enricher ids differ");
+        assertEquals(actual.getEnrichers(), expected.getEnrichers());
+        assertEquals(actual.getPolicies().keySet(), expected.getPolicies().keySet(), "policy ids differ");
+        assertEquals(actual.getPolicies(), expected.getPolicies());
+        assertEquals(actual.getFeeds().keySet(), expected.getFeeds().keySet(), "feed ids differ");
+        assertEquals(actual.getFeeds(), expected.getFeeds());
+        assertTrue(EqualsBuilder.reflectionEquals(actual, expected));
+    }
+    
+    protected void assertRawData(BrooklynMementoRawData actual, BrooklynMementoRawData orig, Deletions deletions) {
+        BrooklynMementoRawData expected = new MementoTweaker(deletions).apply(orig);
+        assertRawData(actual, expected);
+        
+        // double-check that the orig data contains what we think we are deleting!
+        // otherwise we could get a lot of false positive tests.
+        assertTrue(orig.getEntities().keySet().containsAll(deletions.entities));
+        assertTrue(orig.getLocations().keySet().containsAll(deletions.locations));
+        assertTrue(orig.getEnrichers().keySet().containsAll(deletions.enrichers));
+        assertTrue(orig.getPolicies().keySet().containsAll(deletions.policies));
+        assertTrue(orig.getFeeds().keySet().containsAll(deletions.feeds));
+    }
+    
+    protected static class Deletions {
+        final Set<String> entities = Sets.newLinkedHashSet();
+        final Set<String> locations = Sets.newLinkedHashSet();
+        final Set<String> feeds = Sets.newLinkedHashSet();
+        final Set<String> enrichers = Sets.newLinkedHashSet();
+        final Set<String> policies = Sets.newLinkedHashSet();
+        
+        protected Deletions entities(String... vals) {
+            if (vals != null) entities.addAll(Arrays.asList(vals));
+            return this;
+        }
+        protected Deletions locations(String... vals) {
+            if (vals != null) locations.addAll(Arrays.asList(vals));
+            return this;
+        }
+        protected Deletions feeds(String... vals) {
+            if (vals != null) feeds.addAll(Arrays.asList(vals));
+            return this;
+        }
+        protected Deletions enrichers(String... vals) {
+            if (vals != null) enrichers.addAll(Arrays.asList(vals));
+            return this;
+        }
+        protected Deletions policies(String... vals) {
+            if (vals != null) policies.addAll(Arrays.asList(vals));
+            return this;
+        }
+    }
+    
+    public static class MyEnricher extends AbstractEnricher {
+        @SetFromFlag Object obj;
+    }
+    
+    public static class MyPolicy extends AbstractPolicy {
+    }
+    
+    public static class MyFeed extends AbstractFeed {
+    }
+    
+    public static class MyEntity extends TestEntityImpl {
+        @Override protected void initEnrichers() {
+            // no stock enrichers
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherCleanStateTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherCleanStateTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherCleanStateTest.java
new file mode 100644
index 0000000..25d23d5
--- /dev/null
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherCleanStateTest.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.launcher;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotEquals;
+import static org.testng.Assert.assertTrue;
+
+import java.io.File;
+import java.util.concurrent.atomic.AtomicReference;
+
+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.ha.HighAvailabilityMode;
+import org.apache.brooklyn.core.mgmt.persist.PersistMode;
+import org.apache.brooklyn.core.test.entity.TestApplication;
+import org.apache.brooklyn.location.ssh.SshMachineLocation;
+import org.apache.brooklyn.util.os.Os;
+import org.testng.annotations.Test;
+
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.io.Files;
+
+/**
+ * See {@link CleanOrphanedLocationsTest} for more thorough testing. This test is to ensure that
+ * it works through the launcher.
+ */
+public class BrooklynLauncherCleanStateTest extends AbstractBrooklynLauncherRebindTestFixture {
+
+    @Override
+    protected String newTempPersistenceContainerName() {
+        File persistenceDirF = Files.createTempDir();
+        Os.deleteOnExitRecursively(persistenceDirF);
+        return persistenceDirF.getAbsolutePath();
+    }
+    
+    @Test(groups="Integration")
+    public void testCleanStateState() throws Exception {
+        final AtomicReference<Entity> appToKeep = new AtomicReference<>();
+        final AtomicReference<Location> locToKeep = new AtomicReference<>();
+        final AtomicReference<Location> locToDelete = new AtomicReference<>();
+        populatePersistenceDir(persistenceDir, new Function<ManagementContext, Void>() {
+            @Override
+            public Void apply(ManagementContext mgmt) {
+                TestApplication app = mgmt.getEntityManager().createEntity(EntitySpec.create(TestApplication.class));
+                SshMachineLocation loc = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+                SshMachineLocation loc2 = mgmt.getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+                app.addLocations(ImmutableList.of(loc));
+                appToKeep.set(app);
+                locToKeep.set(loc);
+                locToDelete.set(loc2);
+                return null;
+            }});
+
+        File destinationDir = Files.createTempDir();
+        String destination = destinationDir.getAbsolutePath();
+        String destinationLocation = null; // i.e. file system, rather than object store
+        try {
+            // Clean the state
+            BrooklynLauncher launcher = newLauncherDefault(PersistMode.AUTO)
+                    .highAvailabilityMode(HighAvailabilityMode.MASTER)
+                    .webconsole(false);
+            launcher.cleanOrphanedLocations(destination, destinationLocation);
+            launcher.terminate();
+
+            // Sanity checks (copied from BrooklynLauncherRebindTestToFiles#testCopyPersistedState)
+            File entities = new File(Os.mergePaths(destination), "entities");
+            assertTrue(entities.isDirectory(), "entities directory should exist");
+            assertEquals(entities.listFiles().length, 1, "entities directory should contain one file (contained: "+
+                    Joiner.on(", ").join(entities.listFiles()) +")");
+
+            File nodes = new File(Os.mergePaths(destination, "nodes"));
+            assertTrue(nodes.isDirectory(), "nodes directory should exist");
+            assertNotEquals(nodes.listFiles().length, 0, "nodes directory should not be empty");
+
+            // Should now have a usable copy in the destinationDir
+            newLauncherDefault(PersistMode.AUTO)
+                    .webconsole(false)
+                    .persistenceDir(destinationDir)
+                    .start();
+            
+            Entity restoredApp = Iterables.getOnlyElement(lastMgmt().getEntityManager().getEntities());
+            Location restoredLoc = Iterables.getOnlyElement(lastMgmt().getLocationManager().getLocations());
+            assertEquals(restoredApp.getId(), appToKeep.get().getId());
+            assertEquals(restoredLoc.getId(), locToKeep.get().getId());
+        } finally {
+            Os.deleteRecursively(destinationDir);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestFixture.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestFixture.java b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestFixture.java
index 59372e3..a98bc23 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestFixture.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/BrooklynLauncherRebindTestFixture.java
@@ -18,94 +18,32 @@
  */
 package org.apache.brooklyn.launcher;
 
-import org.apache.brooklyn.api.entity.Application;
+import static org.testng.Assert.assertEquals;
+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.api.mgmt.ManagementContext;
-import org.apache.brooklyn.api.mgmt.ha.HighAvailabilityMode;
 import org.apache.brooklyn.core.entity.EntityPredicates;
 import org.apache.brooklyn.core.entity.StartableApplication;
 import org.apache.brooklyn.core.internal.BrooklynProperties;
-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;
-import org.apache.brooklyn.launcher.BrooklynLauncher;
-import org.apache.brooklyn.test.Asserts;
-import org.apache.brooklyn.util.collections.MutableList;
-import org.apache.brooklyn.util.exceptions.FatalConfigurationRuntimeException;
 import org.apache.brooklyn.util.time.Duration;
-
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-import static org.testng.Assert.assertTrue;
-
-import java.util.List;
-
 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.ImmutableMap;
 import com.google.common.collect.Iterables;
 
-public abstract class BrooklynLauncherRebindTestFixture {
+public abstract class BrooklynLauncherRebindTestFixture extends AbstractBrooklynLauncherRebindTestFixture {
 
     @SuppressWarnings("unused")
     private static final Logger log = LoggerFactory.getLogger(BrooklynLauncherRebindTestFixture.class);
     
-    protected String persistenceDir;
-    protected String persistenceLocationSpec;
-    protected List<BrooklynLauncher> launchers = MutableList.of();
-    
-    @BeforeMethod(alwaysRun=true)
-    public void setUp() throws Exception {
-        persistenceDir = newTempPersistenceContainerName();
-    }
-    
-    protected abstract String newTempPersistenceContainerName();
-
-    @AfterMethod(alwaysRun=true)
-    public void tearDown() throws Exception {
-        for (BrooklynLauncher l: launchers) {
-            if (l.isStarted()) {
-                l.terminate();
-                PersistenceObjectStore store = getPersistenceStore(l.getServerDetails().getManagementContext());
-                if (store!=null) store.deleteCompletely();
-            }
-        }
-    }
-
-    protected BrooklynLauncher newLauncherBase() {
-        BrooklynLauncher l = BrooklynLauncher.newInstance()
-            .webconsole(false);
-        launchers.add(l);
-        return l;
-    }
-    protected BrooklynLauncher newLauncherDefault(PersistMode mode) {
-        return newLauncherBase()
-                .managementContext(newManagementContextForTests(null))
-                .persistMode(mode)
-                .persistenceDir(persistenceDir)
-                .persistPeriod(Duration.millis(10));
-    }
-    protected LocalManagementContextForTests newManagementContextForTests(BrooklynProperties props) {
-        if (props==null)
-            return new LocalManagementContextForTests();
-        else
-            return new LocalManagementContextForTests(props);
-    }
-
-    protected ManagementContext lastMgmt() {
-        return Iterables.getLast(launchers).getServerDetails().getManagementContext();
-    }
-    
     @Test
     public void testRebindsToExistingApp() throws Exception {
         populatePersistenceDir(persistenceDir, EntitySpec.create(TestApplication.class).displayName("myorig"));
@@ -212,46 +150,4 @@ public abstract class BrooklynLauncherRebindTestFixture {
     public void testExplicitRebindFailsIfEmpty() throws Exception {
         runRebindFails(PersistMode.REBIND, persistenceDir, "directory is empty");
     }
-
-    protected void runRebindFails(PersistMode persistMode, String dir, String errmsg) throws Exception {
-        try {
-            newLauncherDefault(persistMode)
-                    .persistenceDir(dir)
-                    .start();
-        } catch (FatalConfigurationRuntimeException e) {
-            if (!e.toString().contains(errmsg)) {
-                throw e;
-            }
-        }
-    }
-
-    protected void populatePersistenceDir(String dir, EntitySpec<? extends StartableApplication> appSpec) throws Exception {
-        BrooklynLauncher launcher = newLauncherDefault(PersistMode.CLEAN)
-                .highAvailabilityMode(HighAvailabilityMode.MASTER)
-                .persistenceDir(dir)
-                .application(appSpec)
-                .start();
-        launcher.terminate();
-        assertMementoContainerNonEmptyForTypeEventually("entities");
-    }
-    
-    protected void assertOnlyApp(ManagementContext managementContext, Class<? extends Application> expectedType) {
-        assertEquals(managementContext.getApplications().size(), 1, "apps="+managementContext.getApplications());
-        assertNotNull(Iterables.find(managementContext.getApplications(), Predicates.instanceOf(TestApplication.class), null), "apps="+managementContext.getApplications());
-    }
-    
-    protected void assertMementoContainerNonEmptyForTypeEventually(final String type) {
-        Asserts.succeedsEventually(ImmutableMap.of("timeout", Duration.TEN_SECONDS), new Runnable() {
-            @Override public void run() {
-                getPersistenceStore(lastMgmt()).listContentsWithSubPath(type);
-            }});
-    }
-
-    static PersistenceObjectStore getPersistenceStore(ManagementContext managementContext) {
-        if (managementContext==null) return null;
-        BrooklynMementoPersisterToObjectStore persister = (BrooklynMementoPersisterToObjectStore)managementContext.getRebindManager().getPersister();
-        if (persister==null) return null;
-        return persister.getObjectStore();
-    }
-
 }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedAdjunctsTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedAdjunctsTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedAdjunctsTest.java
new file mode 100644
index 0000000..f9e772a
--- /dev/null
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedAdjunctsTest.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.launcher;
+
+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.mgmt.rebind.mementos.BrooklynMementoRawData;
+import org.apache.brooklyn.api.policy.PolicySpec;
+import org.apache.brooklyn.api.sensor.EnricherSpec;
+import org.apache.brooklyn.api.sensor.Feed;
+import org.apache.brooklyn.core.entity.EntityInternal;
+import org.apache.brooklyn.core.test.entity.TestEntity;
+import org.testng.annotations.Test;
+
+/**
+ * When entity that the adjunct is associated with is deleted, the adjunct can safely be deleted.
+ */
+public class CleanOrphanedAdjunctsTest extends AbstractCleanOrphanedStateTest {
+
+    @Test
+    public void testDeletesOrphanedEnricher() throws Exception {
+        Entity entity = origApp.addChild(EntitySpec.create(TestEntity.class).impl(MyEntity.class));
+        MyEnricher enricher = entity.enrichers().add(EnricherSpec.create(MyEnricher.class));
+        MementoTweaker tweaker = new MementoTweaker(new Deletions().entities(entity.getId()));
+        assertTransformDeletes(new Deletions().enrichers(enricher.getId()), tweaker);
+    }
+    
+    @Test
+    public void testDeletesOrphanedPolicies() throws Exception {
+        Entity entity = origApp.addChild(EntitySpec.create(TestEntity.class).impl(MyEntity.class));
+        MyPolicy policy = entity.policies().add(PolicySpec.create(MyPolicy.class));
+        MementoTweaker tweaker = new MementoTweaker(new Deletions().entities(entity.getId()));
+        assertTransformDeletes(new Deletions().policies(policy.getId()), tweaker);
+    }
+    
+    @Test
+    public void testDeletesOrphanedFeeds() throws Exception {
+        EntityInternal entity = origApp.addChild(EntitySpec.create(TestEntity.class).impl(MyEntity.class));
+        Feed feed = entity.feeds().add(new MyFeed());
+        MementoTweaker tweaker = new MementoTweaker(new Deletions().entities(entity.getId()));
+        assertTransformDeletes(new Deletions().feeds(feed.getId()), tweaker);
+    }
+    
+    @Test
+    public void testKeepsReachableAdjuncts() throws Exception {
+        MyPolicy policy = origApp.policies().add(PolicySpec.create(MyPolicy.class));
+        MyEnricher enricher = origApp.enrichers().add(EnricherSpec.create(MyEnricher.class));
+        Feed feed = origApp.feeds().add(new MyFeed());
+        
+        // Double-check we have the state we expected for the assertions that it is unmodified!
+        BrooklynMementoRawData origData = getRawData();
+        assertTrue(origData.getPolicies().containsKey(policy.getId()));
+        assertTrue(origData.getEnrichers().containsKey(enricher.getId()));
+        assertTrue(origData.getFeeds().containsKey(feed.getId()));
+        
+        assertTransformIsNoop(origData);
+    }
+}

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
index 7be6bd5..258060b 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
@@ -18,36 +18,23 @@
  */
 package org.apache.brooklyn.launcher;
 
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertTrue;
-
-import java.util.Arrays;
-import java.util.Set;
+import static org.testng.Assert.assertFalse;
 
 import org.apache.brooklyn.api.location.Location;
 import org.apache.brooklyn.api.location.LocationSpec;
-import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
+import org.apache.brooklyn.api.location.MachineLocation;
 import org.apache.brooklyn.api.policy.PolicySpec;
 import org.apache.brooklyn.api.sensor.EnricherSpec;
 import org.apache.brooklyn.core.config.ConfigKeys;
-import org.apache.brooklyn.core.enricher.AbstractEnricher;
-import org.apache.brooklyn.core.feed.AbstractFeed;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestFixtureWithApp;
-import org.apache.brooklyn.core.mgmt.rebind.RebindTestUtils;
-import org.apache.brooklyn.core.mgmt.rebind.transformer.impl.DeleteOrphanedLocationsTransformer;
-import org.apache.brooklyn.core.policy.AbstractPolicy;
+import org.apache.brooklyn.core.location.Locations;
 import org.apache.brooklyn.core.sensor.Sensors;
 import org.apache.brooklyn.location.ssh.SshMachineLocation;
-import org.apache.brooklyn.util.collections.MutableMap;
-import org.apache.brooklyn.util.core.flags.SetFromFlag;
-import org.apache.commons.lang.builder.EqualsBuilder;
 import org.testng.annotations.Test;
 
-import com.beust.jcommander.internal.Sets;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
-public class CleanOrphanedLocationsTest extends RebindTestFixtureWithApp {
+public class CleanOrphanedLocationsTest extends AbstractCleanOrphanedStateTest {
 
     @Test
     public void testDeletesOrphanedLocations() throws Exception {
@@ -73,6 +60,37 @@ public class CleanOrphanedLocationsTest extends RebindTestFixtureWithApp {
         assertTransformDeletes(new Deletions().locations(loc1.getId(), loc2.getId()));
     }
 
+    // Tests that we don't accidentally abort or throw exceptions. 
+    @Test
+    public void testHandlesDanglingReference() throws Exception {
+        SshMachineLocation todelete = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.addLocations(ImmutableList.of(todelete));
+        origApp.sensors().set(Sensors.newSensor(Object.class, "mysensor"), loc);
+        origApp.config().set(ConfigKeys.newConfigKey(Object.class, "myconfig"), loc);
+        origApp.tags().addTag(loc);
+        loc.config().set(ConfigKeys.newConfigKey(Object.class, "myconfig"), todelete);
+        
+        Locations.unmanage(todelete);
+        assertFalse(getRawData().getLocations().containsKey(todelete.getId()));
+
+        assertTransformIsNoop();
+    }
+
+    // Previously when iterating over the list, we'd abort on the first null rather than looking
+    // at all the nodes in the list. This test doesn't quite manage to reproduce that. The non-null
+    // dangling references are persisted.
+    @Test
+    public void testHandlesDanglingReferencesInLocationListSurroundingValidReference() throws Exception {
+        SshMachineLocation todelete = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        SshMachineLocation todelete2 = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.addLocations(ImmutableList.of(todelete, loc, todelete2));
+        Locations.unmanage(todelete);
+
+        assertTransformIsNoop();
+    }
+
     @Test
     public void testKeepsLocationsReferencedInEntityLocs() throws Exception {
         SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
@@ -120,7 +138,7 @@ public class CleanOrphanedLocationsTest extends RebindTestFixtureWithApp {
     @Test(groups="WIP", enabled=false)
     public void testKeepsLocationsReferencedInConfigKeyDefault() throws Exception {
         SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
-        origApp.config().set(ConfigKeys.newConfigKey(Object.class, "myconfig", "my description", loc), null);
+        origApp.config().set(ConfigKeys.newConfigKey(MachineLocation.class, "myconfig", "my description", loc), (MachineLocation)null);
         assertTransformIsNoop();
     }
     
@@ -198,90 +216,4 @@ public class CleanOrphanedLocationsTest extends RebindTestFixtureWithApp {
         origApp.feeds().add(feed);
         assertTransformIsNoop();
     }
-    
-    private void assertTransformIsNoop() throws Exception {
-        BrooklynMementoRawData origData = getRawData();
-        BrooklynMementoRawData transformedData = transformRawData(origData);
-        assertRawData(transformedData, origData);
-    }
-
-    private void assertTransformDeletes(Deletions deletions) throws Exception {
-        BrooklynMementoRawData origData = getRawData();
-        BrooklynMementoRawData transformedData = transformRawData(origData);
-        assertRawData(transformedData, origData, deletions);
-    }
-
-    protected BrooklynMementoRawData getRawData() throws Exception {
-        RebindTestUtils.waitForPersisted(origApp);
-        return mgmt().getRebindManager().retrieveMementoRawData();
-    }
-
-    protected BrooklynMementoRawData transformRawData(BrooklynMementoRawData rawData) throws Exception {
-        DeleteOrphanedLocationsTransformer transformer = DeleteOrphanedLocationsTransformer.builder().build();
-        return transformer.transform(rawData);
-    }
-
-    protected void assertRawData(BrooklynMementoRawData actual, BrooklynMementoRawData expected) {
-        // asserting lots of times, to ensure we get a more specific error message!
-        assertEquals(actual.getCatalogItems().keySet(), expected.getCatalogItems().keySet());
-        assertEquals(actual.getCatalogItems(), expected.getCatalogItems());
-        assertEquals(actual.getEntities().keySet(), expected.getEntities().keySet());
-        assertEquals(actual.getEntities(), expected.getEntities());
-        assertEquals(actual.getLocations().keySet(), expected.getLocations().keySet());
-        assertEquals(actual.getLocations(), expected.getLocations());
-        assertEquals(actual.getEnrichers().keySet(), expected.getEnrichers().keySet());
-        assertEquals(actual.getEnrichers(), expected.getEnrichers());
-        assertEquals(actual.getPolicies().keySet(), expected.getPolicies().keySet());
-        assertEquals(actual.getPolicies(), expected.getPolicies());
-        assertEquals(actual.getFeeds().keySet(), expected.getFeeds().keySet());
-        assertEquals(actual.getFeeds(), expected.getFeeds());
-        assertTrue(EqualsBuilder.reflectionEquals(actual, expected));
-    }
-    
-    protected void assertRawData(BrooklynMementoRawData actual, BrooklynMementoRawData orig, Deletions deletions) {
-        BrooklynMementoRawData expected = BrooklynMementoRawData.builder()
-                .catalogItems(orig.getCatalogItems())
-                .entities(orig.getEntities())
-                .locations(MutableMap.<String, String>builder().putAll(orig.getLocations()).removeAll(deletions.locations).build())
-                .feeds(MutableMap.<String, String>builder().putAll(orig.getFeeds()).removeAll(deletions.feeds).build())
-                .enrichers(MutableMap.<String, String>builder().putAll(orig.getEnrichers()).removeAll(deletions.enrichers).build())
-                .policies(MutableMap.<String, String>builder().putAll(orig.getPolicies()).removeAll(deletions.policies).build())
-                .build();
-        assertRawData(actual, expected);
-    }
-    
-    @SuppressWarnings("unused")
-    private static class Deletions {
-        final Set<String> locations = Sets.newLinkedHashSet();
-        final Set<String> feeds = Sets.newLinkedHashSet();
-        final Set<String> enrichers = Sets.newLinkedHashSet();
-        final Set<String> policies = Sets.newLinkedHashSet();
-        
-        Deletions locations(String... vals) {
-            if (vals != null) locations.addAll(Arrays.asList(vals));
-            return this;
-        }
-        Deletions feeds(String... vals) {
-            if (vals != null) feeds.addAll(Arrays.asList(vals));
-            return this;
-        }
-        Deletions enrichers(String... vals) {
-            if (vals != null) enrichers.addAll(Arrays.asList(vals));
-            return this;
-        }
-        Deletions policies(String... vals) {
-            if (vals != null) policies.addAll(Arrays.asList(vals));
-            return this;
-        }
-    }
-    
-    public static class MyEnricher extends AbstractEnricher {
-        @SetFromFlag Object obj;
-    }
-    
-    public static class MyPolicy extends AbstractPolicy {
-    }
-    
-    public static class MyFeed extends AbstractFeed {
-    }
 }

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/660956f7/launcher/src/test/resources/orphaned-locations-test-data/copy-persisted-state-destination/dummy.txt
----------------------------------------------------------------------
diff --git a/launcher/src/test/resources/orphaned-locations-test-data/copy-persisted-state-destination/dummy.txt b/launcher/src/test/resources/orphaned-locations-test-data/copy-persisted-state-destination/dummy.txt
deleted file mode 100644
index e69de29..0000000


[07/11] brooklyn-server git commit: deleting orphaned loss: more testing + code tidy

Posted by al...@apache.org.
deleting orphaned loss: more testing + code tidy


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

Branch: refs/heads/master
Commit: 4d0c4b8c805c7cea399f88f14525ce77f4287d7f
Parents: 5253d4b
Author: Aled Sage <al...@gmail.com>
Authored: Tue Jul 19 23:06:21 2016 +0100
Committer: Ivana Yovcheva <iv...@gmail.com>
Committed: Wed Jul 20 12:18:48 2016 +0300

----------------------------------------------------------------------
 .../DeleteOrphanedLocationsTransformer.java     | 103 ++++++-------------
 .../launcher/CleanOrphanedLocationsTest.java    |  58 +++++++++--
 2 files changed, 81 insertions(+), 80 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/4d0c4b8c/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
index 9f87984..a26d807 100644
--- a/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
+++ b/core/src/main/java/org/apache/brooklyn/core/mgmt/rebind/transformer/impl/DeleteOrphanedLocationsTransformer.java
@@ -18,30 +18,27 @@
  */
 package org.apache.brooklyn.core.mgmt.rebind.transformer.impl;
 
-import java.util.Collection;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-import com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList;
+import javax.xml.xpath.XPathConstants;
+
 import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMemento;
 import org.apache.brooklyn.api.mgmt.rebind.mementos.BrooklynMementoRawData;
 import org.apache.brooklyn.api.mgmt.rebind.mementos.EntityMemento;
 import org.apache.brooklyn.api.mgmt.rebind.mementos.LocationMemento;
-import org.apache.brooklyn.core.mgmt.rebind.dto.BrooklynMementoImpl;
 import org.apache.brooklyn.core.mgmt.rebind.transformer.BrooklynMementoTransformer;
 import org.apache.brooklyn.core.mgmt.rebind.transformer.CompoundTransformer;
-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.xstream.XmlUtil;
+import org.w3c.dom.Node;
 
 import com.google.common.annotations.Beta;
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
-import org.apache.brooklyn.util.core.xstream.XmlUtil;
-import org.w3c.dom.Node;
-
-import javax.xml.xpath.XPathConstants;
 
 @Beta
 public class DeleteOrphanedLocationsTransformer extends CompoundTransformer implements BrooklynMementoTransformer {
@@ -56,11 +53,13 @@ public class DeleteOrphanedLocationsTransformer extends CompoundTransformer impl
 
     public static class Builder extends CompoundTransformer.Builder {
 
+        @Override
         public DeleteOrphanedLocationsTransformer build() {
             return new DeleteOrphanedLocationsTransformer(this);
         }
     }
 
+    @Override
     public BrooklynMementoRawData transform(BrooklynMementoRawData input) {
         Map<String, String> locationsToKeep = findLocationsToKeep(input);
 
@@ -74,55 +73,12 @@ public class DeleteOrphanedLocationsTransformer extends CompoundTransformer impl
                 .build();
     }
 
-    // TODO Work in progress; untested code!
-
+    @Override
     public BrooklynMemento transform(BrooklynMemento input) throws Exception {
-        Set<String> referencedLocationIds = findReferencedLocationIds(input);
-        Set<String> unreferencedLocationIds = Sets.newLinkedHashSet();
-        List<String> toCheck = Lists.newLinkedList(input.getLocationIds());
-
-        while (!toCheck.isEmpty()) {
-            String locationId = toCheck.remove(0);
-            List<String> locationsInHierarchy = MutableList.<String>builder()
-                    .add(locationId)
-                    .addAll(findLocationAncestors(input, locationId))
-                    .addAll(findLocationDescendents(input, locationId))
-                    .build();
-
-            if (containsAny(referencedLocationIds, locationsInHierarchy)) {
-                // keep them all
-            } else {
-                unreferencedLocationIds.addAll(locationsInHierarchy);
-            }
-            toCheck.removeAll(locationsInHierarchy);
-        }
-
-        // TODO What about brooklyn version?
-        return BrooklynMementoImpl.builder()
-                .applicationIds(input.getApplicationIds())
-                .topLevelLocationIds(MutableSet.<String>builder()
-                        .addAll(input.getTopLevelLocationIds())
-                        .removeAll(unreferencedLocationIds)
-                        .build())
-                .entities(input.getEntityMementos())
-                .locations(MutableMap.<String, LocationMemento>builder()
-                        .putAll(input.getLocationMementos())
-                        .removeAll(unreferencedLocationIds)
-                        .build())
-                .policies(input.getPolicyMementos())
-                .enrichers(input.getEnricherMementos())
-                .catalogItems(input.getCatalogItemMementos())
-                .build();
-    }
-
-    public boolean containsAny(Collection<?> container, Iterable<?> contenders) {
-        for (Object contender : contenders) {
-            if (container.contains(contender)) return true;
-        }
-        return false;
+        throw new UnsupportedOperationException();
     }
 
-    public Set<String> findReferencedLocationIds(BrooklynMemento input) {
+    protected Set<String> findReferencedLocationIds(BrooklynMemento input) {
         Set<String> result = Sets.newLinkedHashSet();
 
         for (EntityMemento entity : input.getEntityMementos().values()) {
@@ -131,18 +87,20 @@ public class DeleteOrphanedLocationsTransformer extends CompoundTransformer impl
         return result;
     }
 
+    @VisibleForTesting
     public Map<String, String> findLocationsToKeep(BrooklynMementoRawData input) {
         Map<String, String> locationsToKeep = MutableMap.of();
         Set<String> allReferencedLocations = findAllReferencedLocations(input);
 
-        for (Map.Entry location: input.getLocations().entrySet()) {
+        for (Map.Entry<String, String> location: input.getLocations().entrySet()) {
             if (allReferencedLocations.contains(location.getKey())) {
-                locationsToKeep.put((String) location.getKey(), (String) location.getValue());
+                locationsToKeep.put(location.getKey(), location.getValue());
             }
         }
         return locationsToKeep;
     }
 
+    @VisibleForTesting
     public Set<String> findAllReferencedLocations(BrooklynMementoRawData input) {
         Set<String> allReferencedLocations = MutableSet.of();
 
@@ -155,46 +113,43 @@ public class DeleteOrphanedLocationsTransformer extends CompoundTransformer impl
         return allReferencedLocations;
     }
 
-    private Set<String> searchLocationsToKeep(Map<String, String> entities, String searchInTypePrefix) {
+    protected Set<String> searchLocationsToKeep(Map<String, String> entities, String searchInTypePrefix) {
         Set<String> result = MutableSet.of();
 
-        for(Map.Entry entity: entities.entrySet()) {
+        for(Map.Entry<String, String> entity: entities.entrySet()) {
 
-            String prefix = "/entity";
             String location = "/locations/string";
-            String locationProxy = "/attributes//locationProxy";
-            String locationInConfig = "/config//locationProxy";
+            String locationProxy = "//locationProxy";
 
-            result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) entity.getValue(), searchInTypePrefix+location, XPathConstants.NODESET)));
-            result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) entity.getValue(), searchInTypePrefix+locationProxy, XPathConstants.NODESET)));
-            result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) entity.getValue(), searchInTypePrefix+locationInConfig, XPathConstants.NODESET)));
+            result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(entity.getValue(), searchInTypePrefix+location, XPathConstants.NODESET)));
+            result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(entity.getValue(), searchInTypePrefix+locationProxy, XPathConstants.NODESET)));
         }
 
         return result;
     }
 
-    private Set<String> searchLocationsToKeepInLocations(Map<String, String> locations, Set<String> alreadyReferencedLocations) {
+    protected Set<String> searchLocationsToKeepInLocations(Map<String, String> locations, Set<String> alreadyReferencedLocations) {
         Set<String> result = MutableSet.of();
 
         String prefix = "/location";
         String locationId = "/id";
         String locationChildren = "/children/string";
         String locationParentDirectTag = "/parent";
-        String locationProxy = "/locationConfig//locationProxy";
+        String locationProxy = "//locationProxy";
 
-        for (Map.Entry location: locations.entrySet()) {
+        for (Map.Entry<String, String> location: locations.entrySet()) {
             if (alreadyReferencedLocations.contains(location.getKey())) {
-                result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationId, XPathConstants.NODESET)));
-                result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationChildren, XPathConstants.NODESET)));
-                result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationParentDirectTag, XPathConstants.NODESET)));
-                result.addAll(getAllNodesFromXpath((DTMNodeList) XmlUtil.xpath((String) location.getValue(), prefix+locationProxy, XPathConstants.NODESET)));
+                result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(location.getValue(), prefix+locationId, XPathConstants.NODESET)));
+                result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(location.getValue(), prefix+locationChildren, XPathConstants.NODESET)));
+                result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(location.getValue(), prefix+locationParentDirectTag, XPathConstants.NODESET)));
+                result.addAll(getAllNodesFromXpath((org.w3c.dom.NodeList) XmlUtil.xpath(location.getValue(), prefix+locationProxy, XPathConstants.NODESET)));
             }
         }
 
         return result;
     }
 
-    private Set<String> getAllNodesFromXpath(DTMNodeList nodeList) {
+    protected Set<String> getAllNodesFromXpath(org.w3c.dom.NodeList nodeList) {
         Set<String> result = MutableSet.of();
 
         int i = 0;
@@ -207,7 +162,7 @@ public class DeleteOrphanedLocationsTransformer extends CompoundTransformer impl
         return result;
     }
 
-    public Set<String> findLocationAncestors(BrooklynMemento input, String locationId) {
+    protected Set<String> findLocationAncestors(BrooklynMemento input, String locationId) {
         Set<String> result = Sets.newLinkedHashSet();
 
         String parentId = null;
@@ -220,7 +175,7 @@ public class DeleteOrphanedLocationsTransformer extends CompoundTransformer impl
         return result;
     }
 
-    public Set<String> findLocationDescendents(BrooklynMemento input, String locationId) {
+    protected Set<String> findLocationDescendents(BrooklynMemento input, String locationId) {
         Set<String> result = Sets.newLinkedHashSet();
         List<String> tovisit = Lists.newLinkedList();
 

http://git-wip-us.apache.org/repos/asf/brooklyn-server/blob/4d0c4b8c/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
----------------------------------------------------------------------
diff --git a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
index ff8515a..7be6bd5 100644
--- a/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
+++ b/launcher/src/test/java/org/apache/brooklyn/launcher/CleanOrphanedLocationsTest.java
@@ -39,6 +39,7 @@ import org.apache.brooklyn.core.policy.AbstractPolicy;
 import org.apache.brooklyn.core.sensor.Sensors;
 import org.apache.brooklyn.location.ssh.SshMachineLocation;
 import org.apache.brooklyn.util.collections.MutableMap;
+import org.apache.brooklyn.util.core.flags.SetFromFlag;
 import org.apache.commons.lang.builder.EqualsBuilder;
 import org.testng.annotations.Test;
 
@@ -103,8 +104,31 @@ public class CleanOrphanedLocationsTest extends RebindTestFixtureWithApp {
     }
     
     @Test
-    public void testKeepsParentOfReachableLocation() throws Exception {
-        SshMachineLocation parentLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+    public void testKeepsLocationsReferencedInTag() throws Exception {
+        SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.tags().addTag(loc);
+        assertTransformIsNoop();
+    }
+    
+    /**
+     * TODO Fails because it is persisted as {@code <defaultValue class="locationProxy">biqwd7ukcd</defaultValue>},
+     * rather than having locationProxy as the tag.
+     * 
+     * I (Aled) think we can live without this - hopefully no-one is setting location instances as 
+     * config default values!
+     */
+    @Test(groups="WIP", enabled=false)
+    public void testKeepsLocationsReferencedInConfigKeyDefault() throws Exception {
+        SshMachineLocation loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.config().set(ConfigKeys.newConfigKey(Object.class, "myconfig", "my description", loc), null);
+        assertTransformIsNoop();
+    }
+    
+    @Test
+    public void testKeepsAncestorsOfReachableLocation() throws Exception {
+        SshMachineLocation grandparentLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        SshMachineLocation parentLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .parent((grandparentLoc)));
         SshMachineLocation childLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
                 .parent((parentLoc)));
         origApp.addLocations(ImmutableList.of(childLoc));
@@ -112,11 +136,13 @@ public class CleanOrphanedLocationsTest extends RebindTestFixtureWithApp {
     }
     
     @Test
-    public void testKeepsChildrenOfReachableLocation() throws Exception {
-        SshMachineLocation parentLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+    public void testKeepsDescendantsOfReachableLocation() throws Exception {
+        SshMachineLocation grandparentLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        SshMachineLocation parentLoc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .parent((grandparentLoc)));
         mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
                 .parent((parentLoc)));
-        origApp.addLocations(ImmutableList.of(parentLoc));
+        origApp.addLocations(ImmutableList.of(grandparentLoc));
         assertTransformIsNoop();
     }
     
@@ -128,7 +154,18 @@ public class CleanOrphanedLocationsTest extends RebindTestFixtureWithApp {
         origApp.addLocations(ImmutableList.of(refereeLoc));
         assertTransformIsNoop();
     }
-    
+
+    @Test
+    public void testKeepsTransitiveReferencesOfReachableLocation() throws Exception {
+        Location loc3 = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        Location loc2 = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure(ConfigKeys.newConfigKey(Object.class, "myconfig"), loc3));
+        Location loc1 = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class)
+                .configure(ConfigKeys.newConfigKey(Object.class, "myconfig"), loc2));
+        origApp.addLocations(ImmutableList.of(loc1));
+        assertTransformIsNoop();
+    }
+
     @Test
     public void testKeepsLocationsReferencedByEnricher() throws Exception {
         Location loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
@@ -138,6 +175,14 @@ public class CleanOrphanedLocationsTest extends RebindTestFixtureWithApp {
     }
     
     @Test
+    public void testKeepsLocationsReferencedByEnricherInFlag() throws Exception {
+        Location loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
+        origApp.enrichers().add(EnricherSpec.create(MyEnricher.class)
+                .configure("myobj", loc));
+        assertTransformIsNoop();
+    }
+    
+    @Test
     public void testKeepsLocationsReferencedByPolicy() throws Exception {
         Location loc = mgmt().getLocationManager().createLocation(LocationSpec.create(SshMachineLocation.class));
         origApp.policies().add(PolicySpec.create(MyPolicy.class)
@@ -231,6 +276,7 @@ public class CleanOrphanedLocationsTest extends RebindTestFixtureWithApp {
     }
     
     public static class MyEnricher extends AbstractEnricher {
+        @SetFromFlag Object obj;
     }
     
     public static class MyPolicy extends AbstractPolicy {