You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@brooklyn.apache.org by an...@apache.org on 2015/02/03 12:41:32 UTC

[01/17] incubator-brooklyn git commit: Remove non-Apache repos

Repository: incubator-brooklyn
Updated Branches:
  refs/heads/master 8c5dc9ddf -> 41b2805a8


Remove non-Apache repos

Use altDeploymentRepository if alternative repos needed. brooklyn.deployTo remains only as a marker to activate source and gpg plugins during build.


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

Branch: refs/heads/master
Commit: 85bdd8dd825fc7c564d6b69a05d66672397cc50c
Parents: 7d6c77c
Author: Svetoslav Neykov <sv...@cloudsoftcorp.com>
Authored: Thu Jan 29 15:41:37 2015 +0200
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:06 2015 +0100

----------------------------------------------------------------------
 pom.xml | 56 ++------------------------------------------------------
 1 file changed, 2 insertions(+), 54 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/85bdd8dd/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index ae91755..9f4d9df 100644
--- a/pom.xml
+++ b/pom.xml
@@ -43,7 +43,7 @@
 
       brooklyn.explicitModules :: only builds explicit modules (instead of default modules)
 
-      brooklyn.deployTo={cloudsoftFilesystem,cloudsoftArtifactory,sonatype,apache} ::
+      brooklyn.deployTo={apache} ::
             :: required when deploying; specify the deployment target
 
       javadoc :: build javadoc (adds a minute or two; enabled automatically for target deploy)
@@ -747,7 +747,7 @@
                     <configuration>
                         <mavenExecutorId>forked-path</mavenExecutorId>
                         <useReleaseProfile>false</useReleaseProfile>
-                        <arguments>-Dbrooklyn.deployTo=sonatype</arguments>
+                        <arguments>-Dbrooklyn.deployTo=apache</arguments>
                         <goals>deploy</goals>
                     </configuration>
                 </plugin>
@@ -1881,58 +1881,6 @@
                 </plugin>
             </plugins></build>
         </profile>
-
-        <!-- different properties used to deploy to different locations depending on profiles;
-             default is cloudsoft filesystem repo, but some sources still use cloudsoft artifactory as source
-             (and soon we will support artifactory) -->
-        <profile>
-            <id>cloudsoft-filesystem-repo</id>
-            <activation> <property><name>brooklyn.deployTo</name><value>cloudsoftFilesystem</value></property> </activation>
-            <distributionManagement>
-                <repository>
-                    <id>cloudsoft-deploy-cloudfront-origin-releases</id>
-                    <name>Cloudsoft Release Filesystem repo (used as origin for cloudfront)</name>
-                    <url>scpexe://root@developers-origin.cloudsoftcorp.com/var/www/developers/maven/releases/</url>
-                </repository>
-                <snapshotRepository>
-                    <id>cloudsoft-deploy-cloudfront-origin-snapshots</id>
-                    <name>Cloudsoft Snapshot Filesystem repo (used as origin for cloudfront)</name>
-                    <url>scpexe://root@developers-origin.cloudsoftcorp.com/var/www/developers/maven/snapshots/</url>
-                </snapshotRepository>
-            </distributionManagement>
-        </profile>
-        <profile>
-            <id>cloudsoft-artifactory-repo</id>
-            <activation> <property><name>brooklyn.deployTo</name><value>cloudsoftArtifactory</value></property> </activation>
-            <distributionManagement>
-                <repository>
-                    <id>cloudsoft-deploy-artifactory-release</id>
-                    <name>Cloudsoft Artifactory libs-release-local repo</name>
-                    <url>http://ccweb.cloudsoftcorp.com/maven/libs-release-local/</url>
-                </repository>
-                <snapshotRepository>
-                    <id>cloudsoft-deploy-artifactory-snapshot</id>
-                    <name>Cloudsoft Artifactory libs-snapshot-local repo</name>
-                    <url>http://ccweb.cloudsoftcorp.com/maven/libs-snapshot-local/</url>
-                </snapshotRepository>
-            </distributionManagement>
-        </profile>
-        <profile>
-            <id>sonatype-nexus-repo</id>
-            <activation> <property><name>brooklyn.deployTo</name><value>sonatype</value></property> </activation>
-            <distributionManagement>
-                <repository>
-                    <id>sonatype-nexus-staging</id>
-                    <name>Nexus Release Repository</name>
-                    <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
-                </repository>
-                <snapshotRepository>
-                    <id>sonatype-nexus-snapshots</id>
-                    <name>Sonatype Nexus Snapshots</name>
-                    <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
-                </snapshotRepository>
-            </distributionManagement>
-        </profile>
         <profile>
             <id>apache-repo</id>
             <activation> <property><name>brooklyn.deployTo</name><value>apache</value></property> </activation>


[16/17] incubator-brooklyn git commit: Set Softlayer max name length to a tested 55chars

Posted by an...@apache.org.
Set Softlayer max name length to a tested 55chars

More than this causes different types of error.

Revert "fix JcloudsMachineNamer"
This reverts commit 0adda6374c3450c06e7c2a663e8e953941d6afe0.


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

Branch: refs/heads/master
Commit: 3f612ef08b10bfc0ce798110634f4fa38a5c1201
Parents: 8c5dc9d
Author: Duncan Grant <du...@cloudsoftcorp.com>
Authored: Mon Feb 2 09:51:12 2015 +0000
Committer: Duncan Grant <du...@cloudsoftcorp.com>
Committed: Tue Feb 3 11:25:17 2015 +0000

----------------------------------------------------------------------
 .../location/jclouds/JcloudsMachineNamer.java         | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/3f612ef0/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsMachineNamer.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsMachineNamer.java b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsMachineNamer.java
index 5d531f5..c3f7b28 100644
--- a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsMachineNamer.java
+++ b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsMachineNamer.java
@@ -26,20 +26,22 @@ public class JcloudsMachineNamer extends CloudMachineNamer {
     public JcloudsMachineNamer(ConfigBag setup) {
         super(setup);
     }
-    
+
     /** returns the max length of a VM name for the cloud specified in setup;
      * this value is typically decremented by 9 to make room for jclouds labels */
     public Integer getCustomMaxNameLength() {
         // otherwise, for some known clouds which only allow a short name, use that length
-        if ("vcloud".equals( setup.peek(JcloudsLocationConfig.CLOUD_PROVIDER) )) 
+        if ("vcloud".equals( setup.peek(JcloudsLocationConfig.CLOUD_PROVIDER) ))
             return 24;
-        if ("abiquo".equals( setup.peek(JcloudsLocationConfig.CLOUD_PROVIDER) )) 
+        if ("abiquo".equals( setup.peek(JcloudsLocationConfig.CLOUD_PROVIDER) ))
             return 39;
         if ("google-compute-engine".equals( setup.peek(JcloudsLocationConfig.CLOUD_PROVIDER) ))
             return 39;
+        if ("softlayer".equals( setup.peek(JcloudsLocationConfig.CLOUD_PROVIDER) ))
+            return 55;
         // TODO other cloud max length rules
-        
-        return null;  
+
+        return null;
     }
-    
+
 }


[04/17] incubator-brooklyn git commit: refactor RebindManager to have a RebindIteration

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/55b5f65e/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java b/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
index 8556e61..b1a02c1 100644
--- a/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
+++ b/core/src/main/java/brooklyn/entity/rebind/RebindManagerImpl.java
@@ -20,105 +20,53 @@ package brooklyn.entity.rebind;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
-import java.util.Collection;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 import java.util.concurrent.Callable;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import brooklyn.basic.AbstractBrooklynObject;
 import brooklyn.basic.BrooklynObject;
-import brooklyn.basic.BrooklynObjectInternal;
-import brooklyn.catalog.BrooklynCatalog;
-import brooklyn.catalog.CatalogItem;
-import brooklyn.catalog.CatalogLoadMode;
-import brooklyn.catalog.internal.BasicBrooklynCatalog;
-import brooklyn.catalog.internal.CatalogUtils;
-import brooklyn.config.BrooklynLogging;
-import brooklyn.config.BrooklynLogging.LoggingLevel;
 import brooklyn.config.BrooklynServerConfig;
 import brooklyn.config.ConfigKey;
 import brooklyn.enricher.basic.AbstractEnricher;
 import brooklyn.entity.Application;
-import brooklyn.entity.Entity;
-import brooklyn.entity.Feed;
-import brooklyn.entity.basic.AbstractApplication;
-import brooklyn.entity.basic.AbstractEntity;
 import brooklyn.entity.basic.ConfigKeys;
-import brooklyn.entity.basic.EntityInternal;
-import brooklyn.entity.proxying.InternalEntityFactory;
-import brooklyn.entity.proxying.InternalFactory;
-import brooklyn.entity.proxying.InternalLocationFactory;
-import brooklyn.entity.proxying.InternalPolicyFactory;
 import brooklyn.entity.rebind.persister.BrooklynMementoPersisterToObjectStore;
 import brooklyn.entity.rebind.persister.BrooklynPersistenceUtils;
 import brooklyn.entity.rebind.persister.BrooklynPersistenceUtils.CreateBackupMode;
 import brooklyn.entity.rebind.persister.PersistenceActivityMetrics;
-import brooklyn.event.feed.AbstractFeed;
 import brooklyn.internal.BrooklynFeatureEnablement;
-import brooklyn.location.Location;
-import brooklyn.location.basic.AbstractLocation;
-import brooklyn.location.basic.LocationInternal;
 import brooklyn.management.ExecutionContext;
 import brooklyn.management.ManagementContext;
 import brooklyn.management.Task;
-import brooklyn.management.classloading.BrooklynClassLoadingContext;
 import brooklyn.management.ha.HighAvailabilityManagerImpl;
 import brooklyn.management.ha.ManagementNodeState;
 import brooklyn.management.ha.MementoCopyMode;
-import brooklyn.management.internal.EntityManagerInternal;
-import brooklyn.management.internal.LocationManagerInternal;
 import brooklyn.management.internal.ManagementContextInternal;
 import brooklyn.management.internal.ManagementTransitionInfo.ManagementTransitionMode;
-import brooklyn.mementos.BrooklynMemento;
-import brooklyn.mementos.BrooklynMementoManifest;
-import brooklyn.mementos.BrooklynMementoManifest.EntityMementoManifest;
 import brooklyn.mementos.BrooklynMementoPersister;
-import brooklyn.mementos.BrooklynMementoPersister.LookupContext;
 import brooklyn.mementos.BrooklynMementoRawData;
-import brooklyn.mementos.CatalogItemMemento;
-import brooklyn.mementos.EnricherMemento;
-import brooklyn.mementos.EntityMemento;
-import brooklyn.mementos.FeedMemento;
-import brooklyn.mementos.LocationMemento;
-import brooklyn.mementos.Memento;
-import brooklyn.mementos.PolicyMemento;
 import brooklyn.mementos.TreeNode;
-import brooklyn.policy.Enricher;
-import brooklyn.policy.Policy;
-import brooklyn.policy.basic.AbstractPolicy;
-import brooklyn.util.collections.MutableList;
 import brooklyn.util.collections.MutableMap;
 import brooklyn.util.collections.QuorumCheck;
 import brooklyn.util.collections.QuorumCheck.QuorumChecks;
 import brooklyn.util.exceptions.Exceptions;
 import brooklyn.util.exceptions.RuntimeInterruptedException;
-import brooklyn.util.flags.FlagUtils;
-import brooklyn.util.guava.Maybe;
-import brooklyn.util.javalang.Reflections;
 import brooklyn.util.task.BasicExecutionContext;
 import brooklyn.util.task.ScheduledTask;
 import brooklyn.util.task.Tasks;
-import brooklyn.util.text.Strings;
 import brooklyn.util.time.Duration;
-import brooklyn.util.time.Time;
 
-import com.google.common.base.Preconditions;
 import com.google.common.annotations.Beta;
 import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Optional;
-import com.google.common.base.Stopwatch;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
 
 /** Manages the persistence/rebind process.
  * <p>
@@ -129,7 +77,6 @@ import com.google.common.collect.Sets;
 public class RebindManagerImpl implements RebindManager {
 
     // TODO Use ImmediateDeltaChangeListener if the period is set to 0?
-    // But for MultiFile persister, that is still async
     
     public static final ConfigKey<RebindFailureMode> DANGLING_REFERENCE_FAILURE_MODE =
             ConfigKeys.newConfigKey(RebindFailureMode.class, "rebind.failureMode.danglingRef",
@@ -165,14 +112,14 @@ public class RebindManagerImpl implements RebindManager {
     private volatile boolean readOnlyRunning = false;
     private volatile ScheduledTask readOnlyTask = null;
     private transient Semaphore rebindActive = new Semaphore(1);
-    private transient int readOnlyRebindCount = Integer.MIN_VALUE;
+    private transient AtomicInteger readOnlyRebindCount = new AtomicInteger(Integer.MIN_VALUE);
     
     private volatile BrooklynMementoPersister persistenceStoreAccess;
 
-    private final boolean persistPoliciesEnabled;
-    private final boolean persistEnrichersEnabled;
-    private final boolean persistFeedsEnabled;
-    private final boolean persistCatalogItemsEnabled;
+    final boolean persistPoliciesEnabled;
+    final boolean persistEnrichersEnabled;
+    final boolean persistFeedsEnabled;
+    final boolean persistCatalogItemsEnabled;
     
     private RebindFailureMode danglingRefFailureMode;
     private RebindFailureMode rebindFailureMode;
@@ -229,6 +176,10 @@ public class RebindManagerImpl implements RebindManager {
                 new Object[]{this, persistPoliciesEnabled, persistEnrichersEnabled, persistFeedsEnabled, persistCatalogItemsEnabled});
     }
 
+    public ManagementContextInternal getManagementContext() {
+        return managementContext;
+    }
+    
     /**
      * Must be called before setPerister()
      */
@@ -264,6 +215,11 @@ public class RebindManagerImpl implements RebindManager {
         if (persistenceStoreAccess != null && persistenceStoreAccess != val) {
             throw new IllegalStateException("Dynamically changing persister is not supported: old="+persistenceStoreAccess+"; new="+val);
         }
+        if (persistenceRealChangeListener!=null) {
+            // TODO should probably throw here, but previously we have not -- so let's log for now to be sure it's not happening
+            LOG.warn("Persister reset after listeners have been set", new Throwable("Source of persister reset"));
+        }
+        
         this.persistenceStoreAccess = checkNotNull(val, "persister");
         
         this.persistenceRealChangeListener = new PeriodicDeltaChangeListener(managementContext.getServerExecutionContext(), persistenceStoreAccess, exceptionHandler, persistMetrics, periodicPersistPeriod);
@@ -292,7 +248,7 @@ public class RebindManagerImpl implements RebindManager {
             }
         }
         persistenceRunning = true;
-        readOnlyRebindCount = Integer.MIN_VALUE;
+        readOnlyRebindCount.set(Integer.MIN_VALUE);
         persistenceStoreAccess.enableWriteAccess();
         if (persistenceRealChangeListener != null) persistenceRealChangeListener.start();
     }
@@ -326,7 +282,7 @@ public class RebindManagerImpl implements RebindManager {
         if (persistenceStoreAccess != null) persistenceStoreAccess.disableWriteAccess(true);
         
         readOnlyRunning = true;
-        readOnlyRebindCount = 0;
+        readOnlyRebindCount.set(0);
 
         try {
             rebind(null, null, mode);
@@ -533,596 +489,18 @@ public class RebindManagerImpl implements RebindManager {
     }
     
     protected List<Application> rebindImpl(final ClassLoader classLoader, final RebindExceptionHandler exceptionHandler, ManagementNodeState mode) {
-        checkNotNull(classLoader, "classLoader");
-
-        try {
-            rebindActive.acquire();
-        } catch (InterruptedException e1) { Exceptions.propagate(e1); }
-        RebindTracker.setRebinding();
-        if (ManagementNodeState.isHotProxy(mode))
-            readOnlyRebindCount++;
-
-        Stopwatch timer = Stopwatch.createStarted();
-        try {
-            Reflections reflections = new Reflections(classLoader);
-            RebindContextImpl rebindContext = new RebindContextImpl(exceptionHandler, classLoader);
-            
-            exceptionHandler.onStart(rebindContext);
-            
-            if (mode==ManagementNodeState.HOT_STANDBY || mode==ManagementNodeState.HOT_BACKUP) {
-                rebindContext.setAllReadOnly();
-            } else {
-                Preconditions.checkState(mode==ManagementNodeState.MASTER, "Must be either master or read only to rebind (mode "+mode+")");
-            }
-            
-            LookupContext realLookupContext = new RebindContextLookupContext(managementContext, rebindContext, exceptionHandler);
-            rebindContext.setLookupContext(realLookupContext);
-            
-            // Mutli-phase deserialization.
-            //
-            //  1. deserialize just the "manifest" to find all instances (and their types).
-            //  2. instantiate and reconstruct catalog items
-            //  3. instantiate entities+locations so that inter-entity references can subsequently be set during deserialize (and entity config/state is set).
-            //  4. deserialize the memento
-            //  5. instantiate policies+enricherss+feeds (could perhaps merge this with (3), depending how they are implemented)
-            //  6. reconstruct the entities etc (i.e. calling rebind() on the already-instantiated instances)
-            //  7. add policies+enrichers+feeds to all the entities.
-            //  8. manage the entities
-            
-            // TODO if underlying data-store is changed between first and second manifest read (e.g. to add an
-            // entity), then second phase might try to reconstitute an entity that has not been put in
-            // the rebindContext. This should not affect normal production usage, because rebind is run
-            // against a data-store that is not being written to by other brooklyn instance(s).
-
-            // TODO Rebinding to code in OSGi bundles:
-            // Inferring the catalog item id context:
-            //   * most of the time the creator will be passing "my catalog item id" 
-            //     (or API could also take "BrooklynObject me" as a creation context and the 
-            //     receiver query the creator's catalog item id)
-            //   * look at the context entity of Tasks.current() (if set)
-            //   * propagate the catalog item id when doing setEntity, addChild
-            //   * when none of the above work (or they are wrong) let the user specify the catalog item
-            //
-            //  Precedence of setting the catalog item ID:
-            //   1. User-supplied catalog item ID.
-            //   2. Creating from a catalog item - all items resolved during the creation of a spec
-            //      from a catalog item receive the catalog item's ID as context.
-            //   3. When using the Java API for creating specs get the catalog item ID from the
-            //      context entity of the Tasks.current() task.
-            //   4. Propagate the context catalog item ID to children, adjuncts if they don't have one already.
-
-            //
-            // PHASE ONE
-            //
-
-            //The manifest contains full catalog items mementos. Reading them at this stage means that
-            //we don't support references to entities/locations withing tags.
-            
-            LOG.debug("Rebinding ("+mode+
-                (readOnlyRebindCount>Integer.MIN_VALUE ? ", iteration "+readOnlyRebindCount : "")+
-                ") from "+getPersister().getBackingStoreDescription()+"...");
-
-            BrooklynMementoRawData mementoRawData = persistenceStoreAccess.loadMementoRawData(exceptionHandler);
-            BrooklynMementoManifest mementoManifest = persistenceStoreAccess.loadMementoManifest(mementoRawData, exceptionHandler);
-
-            boolean overwritingMaster = false;
-            boolean isEmpty = mementoManifest.isEmpty();
-            if (mode!=ManagementNodeState.HOT_STANDBY && mode!=ManagementNodeState.HOT_BACKUP) {
-                if (!isEmpty) { 
-                    LOG.info("Rebinding from "+getPersister().getBackingStoreDescription()+" for "+Strings.toLowerCase(Strings.toString(mode))+" "+managementContext.getManagementNodeId()+"...");
-                } else {
-                    LOG.info("Rebind check: no existing state; will persist new items to "+getPersister().getBackingStoreDescription());
-                }
-                
-                if (!managementContext.getEntityManager().getEntities().isEmpty() || !managementContext.getLocationManager().getLocations().isEmpty()) {
-                    // this is discouraged if we were already master
-                    Entity anEntity = Iterables.getFirst(managementContext.getEntityManager().getEntities(), null);
-                    if (anEntity!=null && !((EntityInternal)anEntity).getManagementSupport().isReadOnly()) {
-                        overwritingMaster = true;
-                        LOG.warn("Rebind requested for "+mode+" node "+managementContext.getManagementNodeId()+" "
-                            + "when it already has active state; discouraged, "
-                            + "will likely overwrite: "+managementContext.getEntityManager().getEntities()+" and "+managementContext.getLocationManager().getLocations()+" and more");
-                    }
-                }
-            }
-
-            //
-            // PHASE TWO - build catalog so we can load other things
-            //
-            
-            BrooklynObjectInstantiator instantiator = new BrooklynObjectInstantiator(classLoader, rebindContext, reflections);
-            
-            // Instantiate catalog items
-            if (persistCatalogItemsEnabled) {
-                logRebindingDebug("RebindManager instantiating catalog items: {}", mementoManifest.getCatalogItemIds());
-                for (CatalogItemMemento catalogItemMemento : mementoManifest.getCatalogItemMementos().values()) {
-                    if (LOG.isDebugEnabled()) LOG.debug("RebindManager instantiating catalog item {}", catalogItemMemento);
-                    try {
-                        CatalogItem<?, ?> catalogItem = instantiator.newCatalogItem(catalogItemMemento);
-                        rebindContext.registerCatalogItem(catalogItemMemento.getId(), catalogItem);
-                    } catch (Exception e) {
-                        exceptionHandler.onCreateFailed(BrooklynObjectType.CATALOG_ITEM, catalogItemMemento.getId(), catalogItemMemento.getType(), e);
-                    }
-                }
-            } else {
-                logRebindingDebug("Not rebinding catalog; feature disabled: {}", mementoManifest.getCatalogItemIds());
-            }
-
-            // Reconstruct catalog entries
-            if (persistCatalogItemsEnabled) {
-                logRebindingDebug("RebindManager reconstructing catalog items");
-                for (CatalogItemMemento catalogItemMemento : mementoManifest.getCatalogItemMementos().values()) {
-                    CatalogItem<?, ?> item = rebindContext.getCatalogItem(catalogItemMemento.getId());
-                    logRebindingDebug("RebindManager reconstructing catalog item {}", catalogItemMemento);
-                    if (item == null) {
-                        exceptionHandler.onNotFound(BrooklynObjectType.CATALOG_ITEM, catalogItemMemento.getId());
-                    } else {
-                        try {
-                            item.getRebindSupport().reconstruct(rebindContext, catalogItemMemento);
-                            if (item instanceof AbstractBrooklynObject) {
-                                AbstractBrooklynObject.class.cast(item).setManagementContext(managementContext);
-                            }
-                        } catch (Exception e) {
-                            exceptionHandler.onRebindFailed(BrooklynObjectType.CATALOG_ITEM, item, e);
-                        }
-                    }
-                }
-            }
-            
-            // Register catalogue items with the management context. Loads the bundles in the OSGi framework.
-            CatalogLoadMode catalogLoadMode = managementContext.getConfig().getConfig(BrooklynServerConfig.CATALOG_LOAD_MODE);
-            if (persistCatalogItemsEnabled) {
-                boolean shouldResetCatalog = catalogLoadMode == CatalogLoadMode.LOAD_PERSISTED_STATE
-                        || (!isEmpty && catalogLoadMode == CatalogLoadMode.LOAD_BROOKLYN_CATALOG_URL_IF_NO_PERSISTED_STATE);
-                boolean shouldLoadDefaultCatalog = catalogLoadMode == CatalogLoadMode.LOAD_BROOKLYN_CATALOG_URL
-                        || (isEmpty && catalogLoadMode == CatalogLoadMode.LOAD_BROOKLYN_CATALOG_URL_IF_NO_PERSISTED_STATE);
-                if (shouldResetCatalog) {
-                    // Reset catalog with previously persisted state
-                    logRebindingDebug("RebindManager resetting management context catalog to previously persisted state");
-                    managementContext.getCatalog().reset(rebindContext.getCatalogItems());
-                } else if (shouldLoadDefaultCatalog) {
-                    // Load catalogue as normal
-                    // TODO in read-only mode, should do this less frequently than entities etc
-                    logRebindingDebug("RebindManager loading default catalog");
-                    ((BasicBrooklynCatalog) managementContext.getCatalog()).resetCatalogToContentsAtConfiguredUrl();
-                } else {
-                    // Management context should have taken care of loading the catalogue
-                    Collection<CatalogItem<?, ?>> catalogItems = rebindContext.getCatalogItems();
-                    String message = "RebindManager not resetting catalog to persisted state. Catalog load mode is {}.";
-                    if (!catalogItems.isEmpty() && shouldLogRebinding()) {
-                        LOG.info(message + " There {} {} item{} persisted.", new Object[]{
-                                catalogLoadMode, catalogItems.size() == 1 ? "was" : "were", catalogItems.size(), Strings.s(catalogItems)});
-                    } else if (LOG.isDebugEnabled()) {
-                        logRebindingDebug(message, catalogLoadMode);
-                    }
-                }
-                // TODO destroy old (as above)
-            } else {
-                logRebindingDebug("RebindManager not resetting catalog because catalog persistence is disabled");
-            }
-            
-            
-            //
-            // PHASE THREE
-            //
-            
-            // Instantiate locations
-            logRebindingDebug("RebindManager instantiating locations: {}", mementoManifest.getLocationIdToType().keySet());
-            for (Map.Entry<String, String> entry : mementoManifest.getLocationIdToType().entrySet()) {
-                String locId = entry.getKey();
-                String locType = entry.getValue();
-                if (LOG.isTraceEnabled()) LOG.trace("RebindManager instantiating location {}", locId);
-                
-                try {
-                    Location location = instantiator.newLocation(locId, locType);
-                    rebindContext.registerLocation(locId, location);
-                } catch (Exception e) {
-                    exceptionHandler.onCreateFailed(BrooklynObjectType.LOCATION, locId, locType, e);
-                }
-            }
-            
-            // Instantiate entities
-            logRebindingDebug("RebindManager instantiating entities: {}", mementoManifest.getEntityIdToManifest().keySet());
-            for (Map.Entry<String, EntityMementoManifest> entry : mementoManifest.getEntityIdToManifest().entrySet()) {
-                String entityId = entry.getKey();
-                EntityMementoManifest entityManifest = entry.getValue();
-                String catalogItemId = findCatalogItemId(classLoader, mementoManifest.getEntityIdToManifest(), entityManifest);
-                
-                if (LOG.isTraceEnabled()) LOG.trace("RebindManager instantiating entity {}", entityId);
-                
-                try {
-                    Entity entity = (Entity) instantiator.newEntity(entityId, entityManifest.getType(), catalogItemId);
-                    ((EntityInternal)entity).getManagementSupport().setReadOnly( rebindContext.isReadOnly(entity) );
-                    rebindContext.registerEntity(entityId, entity);
-
-                } catch (Exception e) {
-                    exceptionHandler.onCreateFailed(BrooklynObjectType.ENTITY, entityId, entityManifest.getType(), e);
-                }
-            }
-            
-            
-            //
-            // PHASE FOUR
-            //
-            
-            BrooklynMemento memento = persistenceStoreAccess.loadMemento(mementoRawData, realLookupContext, exceptionHandler);
-            
-            
-            //
-            // PHASE FIVE
-            //
-            
-            // Instantiate policies
-            if (persistPoliciesEnabled) {
-                logRebindingDebug("RebindManager instantiating policies: {}", memento.getPolicyIds());
-                for (PolicyMemento policyMemento : memento.getPolicyMementos().values()) {
-                    logRebindingDebug("RebindManager instantiating policy {}", policyMemento);
-                    
-                    try {
-                        Policy policy = instantiator.newPolicy(policyMemento);
-                        rebindContext.registerPolicy(policyMemento.getId(), policy);
-                    } catch (Exception e) {
-                        exceptionHandler.onCreateFailed(BrooklynObjectType.POLICY, policyMemento.getId(), policyMemento.getType(), e);
-                    }
-                }
-            } else {
-                logRebindingDebug("Not rebinding policies; feature disabled: {}", memento.getPolicyIds());
-            }
-            
-            // Instantiate enrichers
-            if (persistEnrichersEnabled) {
-                logRebindingDebug("RebindManager instantiating enrichers: {}", memento.getEnricherIds());
-                for (EnricherMemento enricherMemento : memento.getEnricherMementos().values()) {
-                    logRebindingDebug("RebindManager instantiating enricher {}", enricherMemento);
-
-                    try {
-                        Enricher enricher = instantiator.newEnricher(enricherMemento);
-                        rebindContext.registerEnricher(enricherMemento.getId(), enricher);
-                    } catch (Exception e) {
-                        exceptionHandler.onCreateFailed(BrooklynObjectType.ENRICHER, enricherMemento.getId(), enricherMemento.getType(), e);
-                    }
-                }
-            } else {
-                logRebindingDebug("Not rebinding enrichers; feature disabled: {}", memento.getEnricherIds());
-            } 
-            
-            // Instantiate feeds
-            if (persistFeedsEnabled) {
-                logRebindingDebug("RebindManager instantiating feeds: {}", memento.getFeedIds());
-                for (FeedMemento feedMemento : memento.getFeedMementos().values()) {
-                    if (LOG.isDebugEnabled()) LOG.debug("RebindManager instantiating feed {}", feedMemento);
-
-                    try {
-                        Feed feed = instantiator.newFeed(feedMemento);
-                        rebindContext.registerFeed(feedMemento.getId(), feed);
-                    } catch (Exception e) {
-                        exceptionHandler.onCreateFailed(BrooklynObjectType.FEED, feedMemento.getId(), feedMemento.getType(), e);
-                    }
-                }
-            } else {
-                logRebindingDebug("Not rebinding feeds; feature disabled: {}", memento.getFeedIds());
-            } 
-
-            //
-            // PHASE SIX
-            //
-            
-            // Reconstruct locations
-            logRebindingDebug("RebindManager reconstructing locations");
-            for (LocationMemento locMemento : sortParentFirst(memento.getLocationMementos()).values()) {
-                Location location = rebindContext.getLocation(locMemento.getId());
-                logRebindingDebug("RebindManager reconstructing location {}", locMemento);
-                if (location == null) {
-                    // usually because of creation-failure, when not using fail-fast
-                    exceptionHandler.onNotFound(BrooklynObjectType.LOCATION, locMemento.getId());
-                } else {
-                    try {
-                        ((LocationInternal)location).getRebindSupport().reconstruct(rebindContext, locMemento);
-                    } catch (Exception e) {
-                        exceptionHandler.onRebindFailed(BrooklynObjectType.LOCATION, location, e);
-                    }
-                }
-            }
-
-            // Reconstruct policies
-            if (persistPoliciesEnabled) {
-                logRebindingDebug("RebindManager reconstructing policies");
-                for (PolicyMemento policyMemento : memento.getPolicyMementos().values()) {
-                    Policy policy = rebindContext.getPolicy(policyMemento.getId());
-                    logRebindingDebug("RebindManager reconstructing policy {}", policyMemento);
-    
-                    if (policy == null) {
-                        // usually because of creation-failure, when not using fail-fast
-                        exceptionHandler.onNotFound(BrooklynObjectType.POLICY, policyMemento.getId());
-                    } else {
-                        try {
-                            policy.getRebindSupport().reconstruct(rebindContext, policyMemento);
-                        } catch (Exception e) {
-                            exceptionHandler.onRebindFailed(BrooklynObjectType.POLICY, policy, e);
-                            rebindContext.unregisterPolicy(policy);
-                        }
-                    }
-                }
-            }
-
-            // Reconstruct enrichers
-            if (persistEnrichersEnabled) {
-                logRebindingDebug("RebindManager reconstructing enrichers");
-                for (EnricherMemento enricherMemento : memento.getEnricherMementos().values()) {
-                    Enricher enricher = rebindContext.getEnricher(enricherMemento.getId());
-                    logRebindingDebug("RebindManager reconstructing enricher {}", enricherMemento);
+        RebindIteration iteration = new RebindIteration(this, mode, classLoader, exceptionHandler,
+            rebindActive, readOnlyRebindCount, rebindMetrics, persistenceStoreAccess);
         
-                    if (enricher == null) {
-                        // usually because of creation-failure, when not using fail-fast
-                        exceptionHandler.onNotFound(BrooklynObjectType.ENRICHER, enricherMemento.getId());
-                    } else {
-                        try {
-                            enricher.getRebindSupport().reconstruct(rebindContext, enricherMemento);
-                        } catch (Exception e) {
-                            exceptionHandler.onRebindFailed(BrooklynObjectType.ENRICHER, enricher, e);
-                            rebindContext.unregisterEnricher(enricher);
-                        }
-                    }
-                }
-            }
-    
-            // Reconstruct feeds
-            if (persistFeedsEnabled) {
-                logRebindingDebug("RebindManager reconstructing feeds");
-                for (FeedMemento feedMemento : memento.getFeedMementos().values()) {
-                    Feed feed = rebindContext.getFeed(feedMemento.getId());
-                    logRebindingDebug("RebindManager reconstructing feed {}", feedMemento);
+        iteration.runFullRebind();
         
-                    if (feed == null) {
-                        // usually because of creation-failure, when not using fail-fast
-                        exceptionHandler.onNotFound(BrooklynObjectType.FEED, feedMemento.getId());
-                    } else {
-                        try {
-                            feed.getRebindSupport().reconstruct(rebindContext, feedMemento);
-                        } catch (Exception e) {
-                            exceptionHandler.onRebindFailed(BrooklynObjectType.FEED, feed, e);
-                            rebindContext.unregisterFeed(feed);
-                        }
-                    }
-
-                }
-            }
-    
-            // Reconstruct entities
-            logRebindingDebug("RebindManager reconstructing entities");
-            for (EntityMemento entityMemento : sortParentFirst(memento.getEntityMementos()).values()) {
-                Entity entity = rebindContext.lookup().lookupEntity(entityMemento.getId());
-                logRebindingDebug("RebindManager reconstructing entity {}", entityMemento);
-    
-                if (entity == null) {
-                    // usually because of creation-failure, when not using fail-fast
-                    exceptionHandler.onNotFound(BrooklynObjectType.ENTITY, entityMemento.getId());
-                } else {
-                    try {
-                        entityMemento.injectTypeClass(entity.getClass());
-                        ((EntityInternal)entity).getRebindSupport().reconstruct(rebindContext, entityMemento);
-                    } catch (Exception e) {
-                        exceptionHandler.onRebindFailed(BrooklynObjectType.ENTITY, entity, e);
-                    }
-                }
-            }
-
-            //
-            // PHASE SEVEN
-            //
-            
-            // Associate policies+enrichers+feeds with entities
-            logRebindingDebug("RebindManager reconstructing entities");
-            for (EntityMemento entityMemento : sortParentFirst(memento.getEntityMementos()).values()) {
-                Entity entity = rebindContext.getEntity(entityMemento.getId());
-                logRebindingDebug("RebindManager reconstructing entity {}", entityMemento);
-    
-                if (entity == null) {
-                    // usually because of creation-failure, when not using fail-fast
-                    exceptionHandler.onNotFound(BrooklynObjectType.ENTITY, entityMemento.getId());
-                } else {
-                    try {
-                        entityMemento.injectTypeClass(entity.getClass());
-                        // TODO these call to the entity which in turn sets the entity on the underlying feeds and enrichers;
-                        // that is taken as the cue to start, but it should not be. start should be a separate call.
-                        ((EntityInternal)entity).getRebindSupport().addPolicies(rebindContext, entityMemento);
-                        ((EntityInternal)entity).getRebindSupport().addEnrichers(rebindContext, entityMemento);
-                        ((EntityInternal)entity).getRebindSupport().addFeeds(rebindContext, entityMemento);
-                    } catch (Exception e) {
-                        exceptionHandler.onRebindFailed(BrooklynObjectType.ENTITY, entity, e);
-                    }
-                }
-            }
-            
-            
-            //
-            // PHASE EIGHT
-            //
-
-            logRebindingDebug("RebindManager managing locations");
-            LocationManagerInternal locationManager = (LocationManagerInternal)managementContext.getLocationManager();
-            Set<String> oldLocations = Sets.newLinkedHashSet(locationManager.getLocationIds());
-            for (Location location: rebindContext.getLocations()) {
-                ManagementTransitionMode oldMode = locationManager.getLastManagementTransitionMode(location.getId());
-                locationManager.setManagementTransitionMode(location, computeMode(managementContext, location, oldMode, rebindContext.isReadOnly(location)) );
-                if (oldMode!=null)
-                    oldLocations.remove(location.getId());
-            }
-            for (Location location: rebindContext.getLocations()) {
-                if (location.getParent()==null) {
-                    // manage all root locations
-                    try {
-                        ((LocationManagerInternal)managementContext.getLocationManager()).manageRebindedRoot(location);
-                    } catch (Exception e) {
-                        exceptionHandler.onManageFailed(BrooklynObjectType.LOCATION, location, e);
-                    }
-                }
-            }
-            // destroy old
-            if (!oldLocations.isEmpty()) BrooklynLogging.log(LOG, overwritingMaster ? BrooklynLogging.LoggingLevel.WARN : BrooklynLogging.LoggingLevel.DEBUG, 
-                "Destroying unused locations on rebind: "+oldLocations);
-            for (String oldLocationId: oldLocations) {
-               locationManager.unmanage(locationManager.getLocation(oldLocationId), ManagementTransitionMode.REBINDING_DESTROYED); 
-            }
-            
-            // Manage the top-level apps (causing everything under them to become managed)
-            logRebindingDebug("RebindManager managing entities");
-            EntityManagerInternal entityManager = (EntityManagerInternal)managementContext.getEntityManager();
-            Set<String> oldEntities = Sets.newLinkedHashSet(entityManager.getEntityIds());
-            for (Entity entity: rebindContext.getEntities()) {
-                ManagementTransitionMode oldMode = entityManager.getLastManagementTransitionMode(entity.getId());
-                entityManager.setManagementTransitionMode(entity, computeMode(managementContext,entity, oldMode, rebindContext.isReadOnly(entity)) );
-                if (oldMode!=null)
-                    oldEntities.remove(entity.getId());
-            }
-            List<Application> apps = Lists.newArrayList();
-            for (String appId : memento.getApplicationIds()) {
-                Entity entity = rebindContext.getEntity(appId);
-                if (entity == null) {
-                    // usually because of creation-failure, when not using fail-fast
-                    exceptionHandler.onNotFound(BrooklynObjectType.ENTITY, appId);
-                } else {
-                    try {
-                        entityManager.manageRebindedRoot(entity);
-                    } catch (Exception e) {
-                        exceptionHandler.onManageFailed(BrooklynObjectType.ENTITY, entity, e);
-                    }
-                    apps.add((Application)entity);
-                }
-            }
-            // destroy old
-            if (!oldLocations.isEmpty()) BrooklynLogging.log(LOG, overwritingMaster ? BrooklynLogging.LoggingLevel.WARN : BrooklynLogging.LoggingLevel.DEBUG, 
-                "Destroying unused entities on rebind: "+oldEntities);
-            for (String oldEntityId: oldEntities) {
-               entityManager.unmanage(entityManager.getEntity(oldEntityId), ManagementTransitionMode.REBINDING_DESTROYED); 
-            }
-
-            exceptionHandler.onDone();
-            
-            rebindMetrics.noteSuccess(Duration.of(timer));
-            noteErrors(exceptionHandler, null);
-            if (firstRebindAppCount==null) {
-                firstRebindAppCount = apps.size();
-                firstRebindEntityCount = rebindContext.getEntities().size();
-                firstRebindItemCount = rebindContext.getAllBrooklynObjects().size();
-            }
-
-            if (!isEmpty) {
-                BrooklynLogging.log(LOG, shouldLogRebinding() ? LoggingLevel.INFO : LoggingLevel.DEBUG, 
-                    "Rebind complete " + "("+mode+(readOnlyRebindCount>=0 ? ", iteration "+readOnlyRebindCount : "")+")" +
-                        " in {}: {} app{}, {} entit{}, {} location{}, {} polic{}, {} enricher{}, {} feed{}, {} catalog item{}", new Object[]{
-                    Time.makeTimeStringRounded(timer), apps.size(), Strings.s(apps),
-                    rebindContext.getEntities().size(), Strings.ies(rebindContext.getEntities()),
-                    rebindContext.getLocations().size(), Strings.s(rebindContext.getLocations()),
-                    rebindContext.getPolicies().size(), Strings.ies(rebindContext.getPolicies()),
-                    rebindContext.getEnrichers().size(), Strings.s(rebindContext.getEnrichers()),
-                    rebindContext.getFeeds().size(), Strings.s(rebindContext.getFeeds()),
-                    rebindContext.getCatalogItems().size(), Strings.s(rebindContext.getCatalogItems())
-                });
-            }
-
-            // Return the top-level applications
-            logRebindingDebug("RebindManager complete; apps: {}", memento.getApplicationIds());
-            return apps;
-
-        } catch (Exception e) {
-            rebindMetrics.noteFailure(Duration.of(timer));
-            
-            Exceptions.propagateIfFatal(e);
-            noteErrors(exceptionHandler, e);
-            throw exceptionHandler.onFailed(e);
-            
-        } finally {
-            rebindActive.release();
-            RebindTracker.reset();
-        }
-    }
-
-    private void noteErrors(final RebindExceptionHandler exceptionHandler, Exception primaryException) {
-        List<Exception> exceptions = exceptionHandler.getExceptions();
-        List<String> warnings = exceptionHandler.getWarnings();
-        if (primaryException!=null || !exceptions.isEmpty() || !warnings.isEmpty()) {
-            List<String> messages = MutableList.<String>of();
-            if (primaryException!=null) messages.add(primaryException.toString());
-            for (Exception e: exceptions) messages.add(e.toString());
-            for (String w: warnings) messages.add(w);
-            rebindMetrics.noteError(messages);
-        }
-    }
-    
-    private String findCatalogItemId(ClassLoader cl, Map<String, EntityMementoManifest> entityIdToManifest, EntityMementoManifest entityManifest) {
-        if (entityManifest.getCatalogItemId() != null) {
-            return entityManifest.getCatalogItemId();
-        }
-
-        if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_INFER_CATALOG_ITEM_ON_REBIND)) {
-            //First check if any of the parent entities has a catalogItemId set.
-            EntityMementoManifest ptr = entityManifest;
-            while (ptr != null) {
-                if (ptr.getCatalogItemId() != null) {
-                    CatalogItem<?, ?> catalogItem = CatalogUtils.getCatalogItemOptionalVersion(managementContext, ptr.getCatalogItemId());
-                    if (catalogItem != null) {
-                        return catalogItem.getId();
-                    } else {
-                        //Couldn't find a catalog item with this id, but return it anyway and
-                        //let the caller deal with the error.
-                        return ptr.getCatalogItemId();
-                    }
-                }
-                if (ptr.getParent() != null) {
-                    ptr = entityIdToManifest.get(ptr.getParent());
-                } else {
-                    ptr = null;
-                }
-            }
-
-            //If no parent entity has the catalogItemId set try to match them by the type we are trying to load.
-            //The current convention is to set catalog item IDs to the java type (for both plain java or CAMP plan) they represent.
-            //This will be applicable only the first time the store is rebinded, while the catalog items don't have the default
-            //version appended to their IDs, but then we will have catalogItemId set on entities so not neede further anyways.
-            BrooklynCatalog catalog = managementContext.getCatalog();
-            ptr = entityManifest;
-            while (ptr != null) {
-                CatalogItem<?, ?> catalogItem = catalog.getCatalogItem(ptr.getType(), BrooklynCatalog.DEFAULT_VERSION);
-                if (catalogItem != null) {
-                    LOG.debug("Inferred catalog item ID "+catalogItem.getId()+" for "+entityManifest+" from ancestor "+ptr);
-                    return catalogItem.getId();
-                }
-                if (ptr.getParent() != null) {
-                    ptr = entityIdToManifest.get(ptr.getParent());
-                } else {
-                    ptr = null;
-                }
-            }
-
-            //As a last resort go through all catalog items trying to load the type and use the first that succeeds.
-            //But first check if can be loaded from the default classpath
-            try {
-                cl.loadClass(entityManifest.getType());
-                return null;
-            } catch (ClassNotFoundException e) {
-            }
-
-            for (CatalogItem<?, ?> item : catalog.getCatalogItems()) {
-                BrooklynClassLoadingContext loader = CatalogUtils.newClassLoadingContext(managementContext, item);
-                boolean canLoadClass = loader.tryLoadClass(entityManifest.getType()).isPresent();
-                if (canLoadClass) {
-                    LOG.warn("Missing catalog item for "+entityManifest.getId()+", inferring as "+item.getId()+" because that is able to load the item");
-                    return item.getId();
-                }
-            }
+        if (firstRebindAppCount==null) {
+            firstRebindAppCount = iteration.getApplications().size();
+            firstRebindEntityCount = iteration.getRebindContext().getEntities().size();
+            firstRebindItemCount = iteration.getRebindContext().getAllBrooklynObjects().size();
         }
-        return null;
-    }
 
-    private BrooklynClassLoadingContext getLoadingContextFromCatalogItemId(String catalogItemId, ClassLoader classLoader, RebindContext rebindContext) {
-        Preconditions.checkNotNull(catalogItemId, "catalogItemId required (should not be null)");
-        CatalogItem<?, ?> catalogItem = rebindContext.lookup().lookupCatalogItem(catalogItemId);
-        if (catalogItem != null) {
-            return CatalogUtils.newClassLoadingContext(managementContext, catalogItem);
-        } else {
-            throw new IllegalStateException("Failed to load catalog item " + catalogItemId + " required for rebinding.");
-        }
+        return iteration.getApplications();
     }
 
     static ManagementTransitionMode computeMode(ManagementContext mgmt, BrooklynObject item, ManagementTransitionMode oldMode, boolean isNowReadOnly) {
@@ -1159,7 +537,7 @@ public class RebindManagerImpl implements RebindManager {
      * TODO Inefficient implementation!
      */
     @VisibleForTesting
-    <T extends TreeNode> Map<String, T> sortParentFirst(Map<String, T> nodes) {
+    static <T extends TreeNode> Map<String, T> sortParentFirst(Map<String, T> nodes) {
         Map<String, T> result = Maps.newLinkedHashMap();
         for (T node : nodes.values()) {
             List<T> tempchain = Lists.newLinkedList();
@@ -1176,245 +554,6 @@ public class RebindManagerImpl implements RebindManager {
         return result;
     }
 
-    private class BrooklynObjectInstantiator {
-
-        private final ClassLoader classLoader;
-        private final RebindContextImpl rebindContext;
-        private final Reflections reflections;
-        
-        private BrooklynObjectInstantiator(ClassLoader classLoader, RebindContextImpl rebindContext, Reflections reflections) {
-            this.classLoader = classLoader;
-            this.rebindContext = rebindContext;
-            this.reflections = reflections;
-        }
-
-        private Entity newEntity(String entityId, String entityType, String catalogItemId) {
-            Class<? extends Entity> entityClazz = load(Entity.class, entityType, catalogItemId, entityId);
-
-            Entity entity;
-            
-            if (InternalFactory.isNewStyle(entityClazz)) {
-                // Not using entityManager.createEntity(EntitySpec) because don't want init() to be called.
-                // Creates an uninitialized entity, but that has correct id + proxy.
-                InternalEntityFactory entityFactory = managementContext.getEntityFactory();
-                entity = entityFactory.constructEntity(entityClazz, Reflections.getAllInterfaces(entityClazz), entityId);
-
-            } else {
-                LOG.warn("Deprecated rebind of entity without no-arg constructor; this may not be supported in future versions: id="+entityId+"; type="+entityType);
-
-                // There are several possibilities for the constructor; find one that works.
-                // Prefer passing in the flags because required for Application to set the management context
-                // TODO Feels very hacky!
-
-                Map<Object,Object> flags = Maps.newLinkedHashMap();
-                flags.put("id", entityId);
-                if (AbstractApplication.class.isAssignableFrom(entityClazz)) flags.put("mgmt", managementContext);
-
-                // TODO document the multiple sources of flags, and the reason for setting the mgmt context *and* supplying it as the flag
-                // (NB: merge reported conflict as the two things were added separately)
-                entity = (Entity) invokeConstructor(null, entityClazz, new Object[] {flags}, new Object[] {flags, null}, new Object[] {null}, new Object[0]);
-
-                // In case the constructor didn't take the Map arg, then also set it here.
-                // e.g. for top-level app instances such as WebClusterDatabaseExampleApp will (often?) not have
-                // interface + constructor.
-                // TODO On serializing the memento, we should capture which interfaces so can recreate
-                // the proxy+spec (including for apps where there's not an obvious interface).
-                FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", entityId), entity);
-                if (entity instanceof AbstractApplication) {
-                    FlagUtils.setFieldsFromFlags(ImmutableMap.of("mgmt", managementContext), entity);
-                }
-                ((AbstractEntity)entity).setManagementContext(managementContext);
-                managementContext.prePreManage(entity);
-            }
-            
-            setCatalogItemId(entity, catalogItemId);
-            return entity;
-        }
-
-        private void setCatalogItemId(BrooklynObject item, String catalogItemId) {
-            if (catalogItemId!=null) {
-                ((BrooklynObjectInternal)item).setCatalogItemId(catalogItemId);
-            }
-        }
-
-        private <T extends BrooklynObject> Class<? extends T> load(Class<T> bType, Memento memento) {
-            return load(bType, memento.getType(), memento.getCatalogItemId(), memento.getId());
-        }
-        @SuppressWarnings("unchecked")
-        private <T extends BrooklynObject> Class<? extends T> load(Class<T> bType, String jType, String catalogItemId, String contextSuchAsId) {
-            checkNotNull(jType, "Type of %s (%s) must not be null", contextSuchAsId, bType.getSimpleName());
-            if (catalogItemId != null) {
-                BrooklynClassLoadingContext loader = getLoadingContextFromCatalogItemId(catalogItemId, classLoader, rebindContext);
-                return loader.loadClass(jType, bType);
-            } else {
-                // we have previously used reflections; not sure if that's needed?
-                try {
-                    return (Class<T>)reflections.loadClass(jType);
-                } catch (Exception e) {
-                    LOG.warn("Unable to load "+jType+" using reflections; will try standard context");
-                }
-
-                if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_INFER_CATALOG_ITEM_ON_REBIND)) {
-                    //Try loading from whichever catalog bundle succeeds.
-                    BrooklynCatalog catalog = managementContext.getCatalog();
-                    for (CatalogItem<?, ?> item : catalog.getCatalogItems()) {
-                        BrooklynClassLoadingContext catalogLoader = CatalogUtils.newClassLoadingContext(managementContext, item);
-                        Maybe<Class<?>> catalogClass = catalogLoader.tryLoadClass(jType);
-                        if (catalogClass.isPresent()) {
-                            return (Class<? extends T>) catalogClass.get();
-                        }
-                    }
-                    throw new IllegalStateException("No catalogItemId specified and can't load class from either classpath of catalog items");
-                } else {
-                    throw new IllegalStateException("No catalogItemId specified and can't load class from classpath");
-                }
-
-            }
-        }
-
-        /**
-         * Constructs a new location, passing to its constructor the location id and all of memento.getFlags().
-         */
-        private Location newLocation(String locationId, String locationType) {
-            Class<? extends Location> locationClazz = reflections.loadClass(locationType, Location.class);
-
-            if (InternalFactory.isNewStyle(locationClazz)) {
-                // Not using loationManager.createLocation(LocationSpec) because don't want init() to be called
-                // TODO Need to rationalise this to move code into methods of InternalLocationFactory.
-                //      But note that we'll change all locations to be entities at some point!
-                // See same code approach used in #newEntity(EntityMemento, Reflections)
-                InternalLocationFactory locationFactory = managementContext.getLocationFactory();
-                Location location = locationFactory.constructLocation(locationClazz);
-                FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", locationId), location);
-                managementContext.prePreManage(location);
-                ((AbstractLocation)location).setManagementContext(managementContext);
-
-                return location;
-            } else {
-                LOG.warn("Deprecated rebind of location without no-arg constructor; this may not be supported in future versions: id="+locationId+"; type="+locationType);
-
-                // There are several possibilities for the constructor; find one that works.
-                // Prefer passing in the flags because required for Application to set the management context
-                // TODO Feels very hacky!
-                Map<String,?> flags = MutableMap.of("id", locationId, "deferConstructionChecks", true);
-
-                return (Location) invokeConstructor(reflections, locationClazz, new Object[] {flags});
-            }
-            // note 'used' config keys get marked in BasicLocationRebindSupport
-        }
-
-        /**
-         * Constructs a new policy, passing to its constructor the policy id and all of memento.getConfig().
-         */
-        private Policy newPolicy(PolicyMemento memento) {
-            String id = memento.getId();
-            Class<? extends Policy> policyClazz = load(Policy.class, memento.getType(), memento.getCatalogItemId(), id);
-            
-            Policy policy;
-            if (InternalFactory.isNewStyle(policyClazz)) {
-                InternalPolicyFactory policyFactory = managementContext.getPolicyFactory();
-                policy = policyFactory.constructPolicy(policyClazz);
-                FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", id), policy);
-                ((AbstractPolicy)policy).setManagementContext(managementContext);
-
-            } else {
-                LOG.warn("Deprecated rebind of policy without no-arg constructor; this may not be supported in future versions: id="+id+"; type="+policyClazz);
-
-                // There are several possibilities for the constructor; find one that works.
-                // Prefer passing in the flags because required for Application to set the management context
-                // TODO Feels very hacky!
-                Map<String, Object> flags = MutableMap.<String, Object>of(
-                    "id", id, 
-                    "deferConstructionChecks", true,
-                    "noConstructionInit", true);
-                flags.putAll(memento.getConfig());
-
-                policy = invokeConstructor(null, policyClazz, new Object[] {flags});
-            }
-            
-            setCatalogItemId(policy, memento.getCatalogItemId());
-            return policy;
-        }
-
-        /**
-         * Constructs a new enricher, passing to its constructor the enricher id and all of memento.getConfig().
-         */
-        private Enricher newEnricher(EnricherMemento memento) {
-            Class<? extends Enricher> enricherClazz = load(Enricher.class, memento);
-            String id = memento.getId();
-
-            Enricher enricher;
-            if (InternalFactory.isNewStyle(enricherClazz)) {
-                InternalPolicyFactory policyFactory = managementContext.getPolicyFactory();
-                enricher = policyFactory.constructEnricher(enricherClazz);
-                FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", id), enricher);
-                ((AbstractEnricher)enricher).setManagementContext(managementContext);
-
-            } else {
-                LOG.warn("Deprecated rebind of enricher without no-arg constructor; this may not be supported in future versions: id="+id+"; type="+enricherClazz);
-
-                // There are several possibilities for the constructor; find one that works.
-                // Prefer passing in the flags because required for Application to set the management context
-                // TODO Feels very hacky!
-                Map<String, Object> flags = MutableMap.<String, Object>of(
-                    "id", id, 
-                    "deferConstructionChecks", true,
-                    "noConstructionInit", true);
-                flags.putAll(memento.getConfig());
-
-                enricher = invokeConstructor(reflections, enricherClazz, new Object[] {flags});
-            }
-            
-            setCatalogItemId(enricher, memento.getCatalogItemId());
-            return enricher;
-        }
-
-        /**
-         * Constructs a new enricher, passing to its constructor the enricher id and all of memento.getConfig().
-         */
-        private Feed newFeed(FeedMemento memento) {
-            Class<? extends Feed> feedClazz = load(Feed.class, memento);
-            String id = memento.getId();
-
-            Feed feed;
-            if (InternalFactory.isNewStyle(feedClazz)) {
-                InternalPolicyFactory policyFactory = managementContext.getPolicyFactory();
-                feed = policyFactory.constructFeed(feedClazz);
-                FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", id), feed);
-                ((AbstractFeed)feed).setManagementContext(managementContext);
-
-            } else {
-                throw new IllegalStateException("rebind of feed without no-arg constructor unsupported: id="+id+"; type="+feedClazz);
-            }
-            
-            setCatalogItemId(feed, memento.getCatalogItemId());
-            return feed;
-        }
-
-        @SuppressWarnings({ "rawtypes" })
-        private CatalogItem<?, ?> newCatalogItem(CatalogItemMemento memento) {
-            String id = memento.getId();
-            // catalog item subtypes are internal to brooklyn, not in osgi
-            String itemType = checkNotNull(memento.getType(), "catalog item type of %s must not be null in memento", id);
-            Class<? extends CatalogItem> clazz = reflections.loadClass(itemType, CatalogItem.class);
-            return invokeConstructor(reflections, clazz, new Object[]{});
-        }
-
-        private <T> T invokeConstructor(Reflections reflections, Class<T> clazz, Object[]... possibleArgs) {
-            for (Object[] args : possibleArgs) {
-                try {
-                    Optional<T> v = Reflections.invokeConstructorWithArgs(clazz, args, true);
-                    if (v.isPresent()) {
-                        return v.get();
-                    }
-                } catch (Exception e) {
-                    throw Exceptions.propagate(e);
-                }
-            }
-            throw new IllegalStateException("Cannot instantiate instance of type "+clazz+"; expected constructor signature not found");
-        }
-    }
-
     /**
      * Wraps a ChangeListener, to log and never propagate any exceptions that it throws.
      * 
@@ -1460,21 +599,8 @@ public class RebindManagerImpl implements RebindManager {
         }
     }
 
-    /** logs at debug, except during subsequent read-only rebinds, in which it logs trace */
-    private void logRebindingDebug(String message, Object... args) {
-        if (shouldLogRebinding()) {
-            LOG.debug(message, args);
-        } else {
-            LOG.trace(message, args);
-        }
-    }
-    
-    protected boolean shouldLogRebinding() {
-        return (readOnlyRebindCount < 5) || (readOnlyRebindCount%1000==0);
-    }
-
     public int getReadOnlyRebindCount() {
-        return readOnlyRebindCount;
+        return readOnlyRebindCount.get();
     }
     
     @Override
@@ -1484,7 +610,7 @@ public class RebindManagerImpl implements RebindManager {
         result.put("rebind", rebindMetrics.asMap());
         result.put("persist", persistMetrics.asMap());
         
-        if (readOnlyRebindCount>=0)
+        if (readOnlyRebindCount.get()>=0)
             result.put("rebindReadOnlyCount", readOnlyRebindCount);
         
         // include first rebind counts, so we know whether we rebinded or not

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/55b5f65e/core/src/main/java/brooklyn/entity/rebind/persister/PersistenceActivityMetrics.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/persister/PersistenceActivityMetrics.java b/core/src/main/java/brooklyn/entity/rebind/persister/PersistenceActivityMetrics.java
index 8315156..1167ce6 100644
--- a/core/src/main/java/brooklyn/entity/rebind/persister/PersistenceActivityMetrics.java
+++ b/core/src/main/java/brooklyn/entity/rebind/persister/PersistenceActivityMetrics.java
@@ -43,7 +43,7 @@ public class PersistenceActivityMetrics {
         count++;
         failureCount++;
         lastFailureTime = System.currentTimeMillis();
-        lastDuration = duration.toMilliseconds();
+        lastDuration = duration!=null ? duration.toMilliseconds() : -1;
     }
 
     public void noteError(String error) {


[17/17] incubator-brooklyn git commit: This closes #500

Posted by an...@apache.org.
This closes #500


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

Branch: refs/heads/master
Commit: 41b2805a8aa8d482bb3cede13942536683e6d540
Parents: bcb4ea4 3f612ef
Author: Andrea Turli <an...@gmail.com>
Authored: Tue Feb 3 12:41:02 2015 +0100
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 12:41:02 2015 +0100

----------------------------------------------------------------------
 .../location/jclouds/JcloudsMachineNamer.java         | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)
----------------------------------------------------------------------



[15/17] incubator-brooklyn git commit: fix bug where missing script dir causes null script dir explicitly set in ssh tool

Posted by an...@apache.org.
fix bug where missing script dir causes null script dir explicitly set in ssh tool

introduced in #476


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

Branch: refs/heads/master
Commit: bcb4ea4fdb146fef9f5b2daf5a57a990bf201517
Parents: 23e755c
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Sun Feb 1 00:30:32 2015 +0000
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:07 2015 +0100

----------------------------------------------------------------------
 .../brooklyn/location/basic/SshMachineLocation.java  |  2 +-
 .../basic/SshMachineLocationIntegrationTest.java     | 15 +++++++++++++++
 .../brooklyn/location/jclouds/JcloudsLocation.java   |  2 +-
 3 files changed, 17 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bcb4ea4f/core/src/main/java/brooklyn/location/basic/SshMachineLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/SshMachineLocation.java b/core/src/main/java/brooklyn/location/basic/SshMachineLocation.java
index 9482d02..172b58c 100644
--- a/core/src/main/java/brooklyn/location/basic/SshMachineLocation.java
+++ b/core/src/main/java/brooklyn/location/basic/SshMachineLocation.java
@@ -647,7 +647,7 @@ public class SshMachineLocation extends AbstractLocation implements MachineLocat
     private Map<String, Object> augmentPropertiesWithSshConfigGivenToProps(Map<String, ?> props) {
         Map<String,Object> augmentedProps = Maps.newHashMap(props);
         for (ConfigKey<?> config : SSH_CONFIG_GIVEN_TO_PROPS) {
-            if (!props.containsKey(config.getName()))
+            if (!augmentedProps.containsKey(config.getName()) && hasConfig(config, true))
                 augmentedProps.put(config.getName(), getConfig(config));
         }
         return augmentedProps;

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bcb4ea4f/core/src/test/java/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/location/basic/SshMachineLocationIntegrationTest.java b/core/src/test/java/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
index 63f5902..9c85e95 100644
--- a/core/src/test/java/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
+++ b/core/src/test/java/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
@@ -114,4 +114,19 @@ public class SshMachineLocationIntegrationTest {
         int rc = sm.execScript("Test script directory execution", ImmutableList.of(command));
         assertEquals(rc, 0);
     }
+    
+    @Test(groups = "Integration")
+    public void testMissingLocationScriptDirIsAlsoOkay() throws Exception {
+        final String command = "echo hello";
+
+        Map<String, Object> locationConfig = ImmutableMap.<String, Object>builder()
+//                .put(SshMachineLocation.SCRIPT_DIR.getName(), "/var/tmp")
+                .build();
+
+        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", locationConfig);
+        SshMachineLocation sm = lhp.obtain();
+
+        int rc = sm.execScript("Test script directory execution", ImmutableList.of(command));
+        assertEquals(rc, 0);
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bcb4ea4f/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
index 7abbaca..37272d4 100644
--- a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
+++ b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
@@ -1694,7 +1694,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation im
                     .configureIfNotNull(CLOUD_REGION_ID, nodeRegion)
                     .configure(CALLER_CONTEXT, setup.get(CALLER_CONTEXT))
                     .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, setup.get(SshMachineLocation.DETECT_MACHINE_DETAILS))
-                    .configure(SshMachineLocation.SCRIPT_DIR, setup.get(SshMachineLocation.SCRIPT_DIR))
+                    .configureIfNotNull(SshMachineLocation.SCRIPT_DIR, setup.get(SshMachineLocation.SCRIPT_DIR))
                     .configureIfNotNull(USE_PORT_FORWARDING, setup.get(USE_PORT_FORWARDING))
                     .configureIfNotNull(PORT_FORWARDER, setup.get(PORT_FORWARDER))
                     .configureIfNotNull(PORT_FORWARDING_MANAGER, setup.get(PORT_FORWARDING_MANAGER)));


[05/17] incubator-brooklyn git commit: refactor RebindManager to have a RebindIteration

Posted by an...@apache.org.
refactor RebindManager to have a RebindIteration

introduce new class and new methods for each phase. (no real changes.)


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

Branch: refs/heads/master
Commit: 55b5f65edc6684ebf8af4c91f8e8b62f2b989348
Parents: 80429aa
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Thu Jan 29 11:24:27 2015 +0000
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:06 2015 +0100

----------------------------------------------------------------------
 .../brooklyn/entity/rebind/RebindIteration.java | 1086 ++++++++++++++++++
 .../entity/rebind/RebindManagerImpl.java        |  930 +--------------
 .../persister/PersistenceActivityMetrics.java   |    2 +-
 3 files changed, 1115 insertions(+), 903 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/55b5f65e/core/src/main/java/brooklyn/entity/rebind/RebindIteration.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/RebindIteration.java b/core/src/main/java/brooklyn/entity/rebind/RebindIteration.java
new file mode 100644
index 0000000..26ec642
--- /dev/null
+++ b/core/src/main/java/brooklyn/entity/rebind/RebindIteration.java
@@ -0,0 +1,1086 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package brooklyn.entity.rebind;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import brooklyn.basic.AbstractBrooklynObject;
+import brooklyn.basic.BrooklynObject;
+import brooklyn.basic.BrooklynObjectInternal;
+import brooklyn.catalog.BrooklynCatalog;
+import brooklyn.catalog.CatalogItem;
+import brooklyn.catalog.CatalogLoadMode;
+import brooklyn.catalog.internal.BasicBrooklynCatalog;
+import brooklyn.catalog.internal.CatalogUtils;
+import brooklyn.config.BrooklynLogging;
+import brooklyn.config.BrooklynLogging.LoggingLevel;
+import brooklyn.config.BrooklynServerConfig;
+import brooklyn.enricher.basic.AbstractEnricher;
+import brooklyn.entity.Application;
+import brooklyn.entity.Entity;
+import brooklyn.entity.Feed;
+import brooklyn.entity.basic.AbstractApplication;
+import brooklyn.entity.basic.AbstractEntity;
+import brooklyn.entity.basic.EntityInternal;
+import brooklyn.entity.proxying.InternalEntityFactory;
+import brooklyn.entity.proxying.InternalFactory;
+import brooklyn.entity.proxying.InternalLocationFactory;
+import brooklyn.entity.proxying.InternalPolicyFactory;
+import brooklyn.entity.rebind.RebindManagerImpl.RebindTracker;
+import brooklyn.entity.rebind.persister.PersistenceActivityMetrics;
+import brooklyn.event.feed.AbstractFeed;
+import brooklyn.internal.BrooklynFeatureEnablement;
+import brooklyn.location.Location;
+import brooklyn.location.basic.AbstractLocation;
+import brooklyn.location.basic.LocationInternal;
+import brooklyn.management.classloading.BrooklynClassLoadingContext;
+import brooklyn.management.ha.ManagementNodeState;
+import brooklyn.management.internal.EntityManagerInternal;
+import brooklyn.management.internal.LocationManagerInternal;
+import brooklyn.management.internal.ManagementContextInternal;
+import brooklyn.management.internal.ManagementTransitionInfo.ManagementTransitionMode;
+import brooklyn.mementos.BrooklynMemento;
+import brooklyn.mementos.BrooklynMementoManifest;
+import brooklyn.mementos.BrooklynMementoManifest.EntityMementoManifest;
+import brooklyn.mementos.BrooklynMementoPersister;
+import brooklyn.mementos.BrooklynMementoPersister.LookupContext;
+import brooklyn.mementos.BrooklynMementoRawData;
+import brooklyn.mementos.CatalogItemMemento;
+import brooklyn.mementos.EnricherMemento;
+import brooklyn.mementos.EntityMemento;
+import brooklyn.mementos.FeedMemento;
+import brooklyn.mementos.LocationMemento;
+import brooklyn.mementos.Memento;
+import brooklyn.mementos.PolicyMemento;
+import brooklyn.mementos.TreeNode;
+import brooklyn.policy.Enricher;
+import brooklyn.policy.Policy;
+import brooklyn.policy.basic.AbstractPolicy;
+import brooklyn.util.collections.MutableList;
+import brooklyn.util.collections.MutableMap;
+import brooklyn.util.exceptions.Exceptions;
+import brooklyn.util.flags.FlagUtils;
+import brooklyn.util.guava.Maybe;
+import brooklyn.util.javalang.Reflections;
+import brooklyn.util.text.Strings;
+import brooklyn.util.time.Duration;
+import brooklyn.util.time.Time;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Stopwatch;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+/**
+Multi-phase deserialization:
+
+<ul>
+<li> 1. load the manifest files and populate the summaries (ID+type) in {@link BrooklynMementoManifest}
+<li> 2. instantiate and reconstruct catalog items
+<li> 3. instantiate entities+locations -- so that inter-entity references can subsequently 
+       be set during deserialize (and entity config/state is set).
+<li> 4. deserialize the manifests to instantiate the mementos
+<li> 5. instantiate policies+enrichers+feeds 
+        (could probably merge this with (3), depending how they are implemented)
+<li> 6. reconstruct the locations, policies, etc, then finally entities -- setting all fields and then calling 
+        {@link RebindSupport#reconstruct(RebindContext, Memento)}
+<li> 7. associate policies+enrichers+feeds to all the entities
+<li> 8. manage the entities
+</ul>
+
+ If underlying data-store is changed between first and second manifest read (e.g. to add an
+ entity), then second phase might try to reconstitute an entity that has not been put in
+ the rebindContext. This should not affect normal production usage, because rebind is run
+ against a data-store that is not being written to by other brooklyn instance(s).
+ But clearly it would be desirable to have better locking possible against the backing store.
+ 
+<p>
+ When rebinding to code in OSGi bundles, thecatalog item id context is inferred as follows:
+   * most of the time the creator will be passing "my catalog item id" 
+     (or API could also take "BrooklynObject me" as a creation context and the 
+     receiver query the creator's catalog item id)
+   * look at the context entity of Tasks.current() (if set)
+   * propagate the catalog item id when doing setEntity, addChild
+   * when none of the above work (or they are wrong) let the user specify the catalog item
+<p>
+  Precedence of setting the catalog item ID:
+   1. User-supplied catalog item ID.
+   2. Creating from a catalog item - all items resolved during the creation of a spec
+      from a catalog item receive the catalog item's ID as context.
+   3. When using the Java API for creating specs get the catalog item ID from the
+      context entity of the Tasks.current() task.
+   4. Propagate the context catalog item ID to children, adjuncts if they don't have one already.
+*/
+public class RebindIteration {
+
+    private static final Logger LOG = LoggerFactory.getLogger(RebindIteration.class);
+    
+    private final RebindManagerImpl rebindManager;
+    
+    private final ClassLoader classLoader;
+    private final RebindExceptionHandler exceptionHandler;
+    private final ManagementNodeState mode;
+    private final ManagementContextInternal managementContext;
+
+    private final Semaphore rebindActive; 
+    private final AtomicInteger readOnlyRebindCount;
+    private final PersistenceActivityMetrics rebindMetrics;
+    private final BrooklynMementoPersister persistenceStoreAccess;
+    
+    private final AtomicBoolean iterationStarted = new AtomicBoolean();
+    private final RebindContextImpl rebindContext;
+    private final Reflections reflections;
+    private final LookupContext lookupContext;
+    private final BrooklynObjectInstantiator instantiator;
+    
+    // populated in the course of a run
+    
+    // set on run start
+    
+    private Stopwatch timer;
+    /** phase is used to ensure our steps are run as we've expected, and documented (in javadoc at top).
+     * it's worth the extra effort due to the complication and the subtleties. */
+    private int phase = 0;
+
+    // set in first phase
+    
+    private BrooklynMementoRawData mementoRawData;
+    private BrooklynMementoManifest mementoManifest;
+    private Boolean overwritingMaster;
+    private Boolean isEmpty;
+
+    // set later on
+    
+    private BrooklynMemento memento;
+
+    // set near the end
+    
+    private List<Application> applications;
+
+    
+    public RebindIteration(RebindManagerImpl rebindManager, 
+            ManagementNodeState mode,
+            ClassLoader classLoader, RebindExceptionHandler exceptionHandler,
+            Semaphore rebindActive, AtomicInteger readOnlyRebindCount, PersistenceActivityMetrics rebindMetrics, BrooklynMementoPersister persistenceStoreAccess
+            ) {
+        // NB: there is no particularly deep meaning in what is passed in vs what is lookup up from the RebindManager which calls us
+        // (this is simply a refactoring of previous code to a new class)
+        
+        this.rebindManager = rebindManager;
+        
+        this.mode = mode;
+        this.classLoader = checkNotNull(classLoader, "classLoader");
+        this.exceptionHandler = checkNotNull(exceptionHandler, "exceptionHandler");
+        
+        this.rebindActive = rebindActive; 
+        this.readOnlyRebindCount = readOnlyRebindCount;
+        this.rebindMetrics = rebindMetrics;
+        this.persistenceStoreAccess = persistenceStoreAccess;
+        
+        managementContext = rebindManager.getManagementContext();
+        rebindContext = new RebindContextImpl(exceptionHandler, classLoader);
+        reflections = new Reflections(classLoader);
+        lookupContext = new RebindContextLookupContext(managementContext, rebindContext, exceptionHandler);
+        rebindContext.setLookupContext(lookupContext);
+        instantiator = new BrooklynObjectInstantiator(classLoader, rebindContext, reflections);
+        
+        if (mode==ManagementNodeState.HOT_STANDBY || mode==ManagementNodeState.HOT_BACKUP) {
+            rebindContext.setAllReadOnly();
+        } else {
+            Preconditions.checkState(mode==ManagementNodeState.MASTER, "Must be either master or read only to rebind (mode "+mode+")");
+        }
+    }
+
+    public List<Application> getApplications() {
+        return applications;
+    }
+    
+    RebindContextImpl getRebindContext() {
+        return rebindContext;
+    }
+    
+    public void runFullRebind() {
+        runWithLock(new Callable<Void>() {
+           public Void call() throws Exception {
+               
+               loadManifestFiles();
+               rebuildCatalog();
+               instantiateLocationsAndEntities();
+               instantiateMementos();
+               instantiateAdjuncts(instantiator); 
+               reconstructEverything();
+               associateAdjunctsWithEntities();
+               manageTheObjects();
+               finishingUp();
+               
+               return null;
+           }
+        });
+    }
+    
+    protected void runWithLock(Callable<?> target) {
+        if (iterationStarted.getAndSet(true)) {
+            throw new IllegalStateException("Iteration "+this+" has already run; create a new instance for another rebind pass.");
+        }
+        try {
+            rebindActive.acquire();
+        } catch (InterruptedException e) { Exceptions.propagate(e); }
+        try {
+            RebindTracker.setRebinding();
+            if (ManagementNodeState.isHotProxy(mode))
+                readOnlyRebindCount.incrementAndGet();
+
+            timer = Stopwatch.createStarted();
+            exceptionHandler.onStart(rebindContext);
+
+            target.call();
+            
+            exceptionHandler.onDone();
+            
+            rebindMetrics.noteSuccess(Duration.of(timer));
+            noteErrors(exceptionHandler, null);
+            
+        } catch (Exception e) {
+            rebindMetrics.noteFailure(Duration.of(timer));
+            
+            Exceptions.propagateIfFatal(e);
+            noteErrors(exceptionHandler, e);
+            throw exceptionHandler.onFailed(e);
+            
+        } finally {
+            rebindActive.release();
+            RebindTracker.reset();
+        }
+    }
+    
+    protected void checkEnteringPhase(int targetPhase) {
+        phase++;
+        checkContinuingPhase(targetPhase);
+    }
+    protected void checkContinuingPhase(int targetPhase) {
+        if (targetPhase!=phase)
+            throw new IllegalStateException("Phase mismatch: should be phase "+targetPhase+" but is currently "+phase);
+    }
+    
+    protected void loadManifestFiles() throws Exception {
+        checkEnteringPhase(1);
+
+        //The manifest contains full catalog items mementos. Reading them at this stage means that
+        //we don't support references to entities/locations withing tags.
+
+        LOG.debug("Rebinding ("+mode+
+            (readOnlyRebindCount.get()>Integer.MIN_VALUE ? ", iteration "+readOnlyRebindCount : "")+
+            ") from "+rebindManager.getPersister().getBackingStoreDescription()+"...");
+
+        if (mementoRawData!=null || mementoManifest!=null)
+            throw new IllegalStateException("Memento data is already set");
+        
+        mementoRawData = persistenceStoreAccess.loadMementoRawData(exceptionHandler);
+        mementoManifest = persistenceStoreAccess.loadMementoManifest(mementoRawData, exceptionHandler);
+
+        determineStateFromManifestFiles();
+    }
+
+    protected void determineStateFromManifestFiles() {
+        checkContinuingPhase(1);
+
+        overwritingMaster = false;
+        isEmpty = mementoManifest.isEmpty();
+
+        if (mode!=ManagementNodeState.HOT_STANDBY && mode!=ManagementNodeState.HOT_BACKUP) {
+            if (!isEmpty) { 
+                LOG.info("Rebinding from "+getPersister().getBackingStoreDescription()+" for "+Strings.toLowerCase(Strings.toString(mode))+" "+managementContext.getManagementNodeId()+"...");
+            } else {
+                LOG.info("Rebind check: no existing state; will persist new items to "+getPersister().getBackingStoreDescription());
+            }
+
+            if (!managementContext.getEntityManager().getEntities().isEmpty() || !managementContext.getLocationManager().getLocations().isEmpty()) {
+                // this is discouraged if we were already master
+                Entity anEntity = Iterables.getFirst(managementContext.getEntityManager().getEntities(), null);
+                if (anEntity!=null && !((EntityInternal)anEntity).getManagementSupport().isReadOnly()) {
+                    overwritingMaster = true;
+                    LOG.warn("Rebind requested for "+mode+" node "+managementContext.getManagementNodeId()+" "
+                        + "when it already has active state; discouraged, "
+                        + "will likely overwrite: "+managementContext.getEntityManager().getEntities()+" and "+managementContext.getLocationManager().getLocations()+" and more");
+                }
+            }
+        }
+    }
+
+    private void rebuildCatalog() {
+        
+        // build catalog early so we can load other things
+        checkEnteringPhase(2);
+        
+        // Instantiate catalog items
+        if (rebindManager.persistCatalogItemsEnabled) {
+            logRebindingDebug("RebindManager instantiating catalog items: {}", mementoManifest.getCatalogItemIds());
+            for (CatalogItemMemento catalogItemMemento : mementoManifest.getCatalogItemMementos().values()) {
+                if (LOG.isDebugEnabled()) LOG.debug("RebindManager instantiating catalog item {}", catalogItemMemento);
+                try {
+                    CatalogItem<?, ?> catalogItem = instantiator.newCatalogItem(catalogItemMemento);
+                    rebindContext.registerCatalogItem(catalogItemMemento.getId(), catalogItem);
+                } catch (Exception e) {
+                    exceptionHandler.onCreateFailed(BrooklynObjectType.CATALOG_ITEM, catalogItemMemento.getId(), catalogItemMemento.getType(), e);
+                }
+            }
+        } else {
+            logRebindingDebug("Not rebinding catalog; feature disabled: {}", mementoManifest.getCatalogItemIds());
+        }
+
+        // Reconstruct catalog entries
+        if (rebindManager.persistCatalogItemsEnabled) {
+            logRebindingDebug("RebindManager reconstructing catalog items");
+            for (CatalogItemMemento catalogItemMemento : mementoManifest.getCatalogItemMementos().values()) {
+                CatalogItem<?, ?> item = rebindContext.getCatalogItem(catalogItemMemento.getId());
+                logRebindingDebug("RebindManager reconstructing catalog item {}", catalogItemMemento);
+                if (item == null) {
+                    exceptionHandler.onNotFound(BrooklynObjectType.CATALOG_ITEM, catalogItemMemento.getId());
+                } else {
+                    try {
+                        item.getRebindSupport().reconstruct(rebindContext, catalogItemMemento);
+                        if (item instanceof AbstractBrooklynObject) {
+                            AbstractBrooklynObject.class.cast(item).setManagementContext(managementContext);
+                        }
+                    } catch (Exception e) {
+                        exceptionHandler.onRebindFailed(BrooklynObjectType.CATALOG_ITEM, item, e);
+                    }
+                }
+            }
+        }
+        
+        // Register catalogue items with the management context. Loads the bundles in the OSGi framework.
+        CatalogLoadMode catalogLoadMode = managementContext.getConfig().getConfig(BrooklynServerConfig.CATALOG_LOAD_MODE);
+        if (rebindManager.persistCatalogItemsEnabled) {
+            boolean shouldResetCatalog = catalogLoadMode == CatalogLoadMode.LOAD_PERSISTED_STATE
+                    || (!isEmpty && catalogLoadMode == CatalogLoadMode.LOAD_BROOKLYN_CATALOG_URL_IF_NO_PERSISTED_STATE);
+            boolean shouldLoadDefaultCatalog = catalogLoadMode == CatalogLoadMode.LOAD_BROOKLYN_CATALOG_URL
+                    || (isEmpty && catalogLoadMode == CatalogLoadMode.LOAD_BROOKLYN_CATALOG_URL_IF_NO_PERSISTED_STATE);
+            if (shouldResetCatalog) {
+                // Reset catalog with previously persisted state
+                logRebindingDebug("RebindManager resetting management context catalog to previously persisted state");
+                managementContext.getCatalog().reset(rebindContext.getCatalogItems());
+            } else if (shouldLoadDefaultCatalog) {
+                // Load catalogue as normal
+                // TODO in read-only mode, should do this less frequently than entities etc
+                logRebindingDebug("RebindManager loading default catalog");
+                ((BasicBrooklynCatalog) managementContext.getCatalog()).resetCatalogToContentsAtConfiguredUrl();
+            } else {
+                // Management context should have taken care of loading the catalogue
+                Collection<CatalogItem<?, ?>> catalogItems = rebindContext.getCatalogItems();
+                String message = "RebindManager not resetting catalog to persisted state. Catalog load mode is {}.";
+                if (!catalogItems.isEmpty() && shouldLogRebinding()) {
+                    LOG.info(message + " There {} {} item{} persisted.", new Object[]{
+                            catalogLoadMode, catalogItems.size() == 1 ? "was" : "were", catalogItems.size(), Strings.s(catalogItems)});
+                } else if (LOG.isDebugEnabled()) {
+                    logRebindingDebug(message, catalogLoadMode);
+                }
+            }
+            // TODO destroy old (as above)
+        } else {
+            logRebindingDebug("RebindManager not resetting catalog because catalog persistence is disabled");
+        }
+    }
+
+    private void instantiateLocationsAndEntities() {
+
+        checkEnteringPhase(3);
+        
+        // Instantiate locations
+        logRebindingDebug("RebindManager instantiating locations: {}", mementoManifest.getLocationIdToType().keySet());
+        for (Map.Entry<String, String> entry : mementoManifest.getLocationIdToType().entrySet()) {
+            String locId = entry.getKey();
+            String locType = entry.getValue();
+            if (LOG.isTraceEnabled()) LOG.trace("RebindManager instantiating location {}", locId);
+            
+            try {
+                Location location = instantiator.newLocation(locId, locType);
+                rebindContext.registerLocation(locId, location);
+            } catch (Exception e) {
+                exceptionHandler.onCreateFailed(BrooklynObjectType.LOCATION, locId, locType, e);
+            }
+        }
+        
+        // Instantiate entities
+        logRebindingDebug("RebindManager instantiating entities: {}", mementoManifest.getEntityIdToManifest().keySet());
+        for (Map.Entry<String, EntityMementoManifest> entry : mementoManifest.getEntityIdToManifest().entrySet()) {
+            String entityId = entry.getKey();
+            EntityMementoManifest entityManifest = entry.getValue();
+            String catalogItemId = findCatalogItemId(classLoader, mementoManifest.getEntityIdToManifest(), entityManifest);
+            
+            if (LOG.isTraceEnabled()) LOG.trace("RebindManager instantiating entity {}", entityId);
+            
+            try {
+                Entity entity = (Entity) instantiator.newEntity(entityId, entityManifest.getType(), catalogItemId);
+                ((EntityInternal)entity).getManagementSupport().setReadOnly( rebindContext.isReadOnly(entity) );
+                rebindContext.registerEntity(entityId, entity);
+
+            } catch (Exception e) {
+                exceptionHandler.onCreateFailed(BrooklynObjectType.ENTITY, entityId, entityManifest.getType(), e);
+            }
+        }
+    }
+
+    private void instantiateMementos() throws IOException {
+        
+        checkEnteringPhase(4);
+        
+        memento = persistenceStoreAccess.loadMemento(mementoRawData, lookupContext, exceptionHandler);
+    }
+
+    private void instantiateAdjuncts(BrooklynObjectInstantiator instantiator) {
+        
+        checkEnteringPhase(5);
+        
+        // Instantiate policies
+        if (rebindManager.persistPoliciesEnabled) {
+            logRebindingDebug("RebindManager instantiating policies: {}", memento.getPolicyIds());
+            for (PolicyMemento policyMemento : memento.getPolicyMementos().values()) {
+                logRebindingDebug("RebindManager instantiating policy {}", policyMemento);
+                
+                try {
+                    Policy policy = instantiator.newPolicy(policyMemento);
+                    rebindContext.registerPolicy(policyMemento.getId(), policy);
+                } catch (Exception e) {
+                    exceptionHandler.onCreateFailed(BrooklynObjectType.POLICY, policyMemento.getId(), policyMemento.getType(), e);
+                }
+            }
+        } else {
+            logRebindingDebug("Not rebinding policies; feature disabled: {}", memento.getPolicyIds());
+        }
+        
+        // Instantiate enrichers
+        if (rebindManager.persistEnrichersEnabled) {
+            logRebindingDebug("RebindManager instantiating enrichers: {}", memento.getEnricherIds());
+            for (EnricherMemento enricherMemento : memento.getEnricherMementos().values()) {
+                logRebindingDebug("RebindManager instantiating enricher {}", enricherMemento);
+
+                try {
+                    Enricher enricher = instantiator.newEnricher(enricherMemento);
+                    rebindContext.registerEnricher(enricherMemento.getId(), enricher);
+                } catch (Exception e) {
+                    exceptionHandler.onCreateFailed(BrooklynObjectType.ENRICHER, enricherMemento.getId(), enricherMemento.getType(), e);
+                }
+            }
+        } else {
+            logRebindingDebug("Not rebinding enrichers; feature disabled: {}", memento.getEnricherIds());
+        } 
+        
+        // Instantiate feeds
+        if (rebindManager.persistFeedsEnabled) {
+            logRebindingDebug("RebindManager instantiating feeds: {}", memento.getFeedIds());
+            for (FeedMemento feedMemento : memento.getFeedMementos().values()) {
+                if (LOG.isDebugEnabled()) LOG.debug("RebindManager instantiating feed {}", feedMemento);
+
+                try {
+                    Feed feed = instantiator.newFeed(feedMemento);
+                    rebindContext.registerFeed(feedMemento.getId(), feed);
+                } catch (Exception e) {
+                    exceptionHandler.onCreateFailed(BrooklynObjectType.FEED, feedMemento.getId(), feedMemento.getType(), e);
+                }
+            }
+        } else {
+            logRebindingDebug("Not rebinding feeds; feature disabled: {}", memento.getFeedIds());
+        }
+    }
+
+    private void reconstructEverything() {
+        
+        checkEnteringPhase(6);
+        
+        // Reconstruct locations
+        logRebindingDebug("RebindManager reconstructing locations");
+        for (LocationMemento locMemento : sortParentFirst(memento.getLocationMementos()).values()) {
+            Location location = rebindContext.getLocation(locMemento.getId());
+            logRebindingDebug("RebindManager reconstructing location {}", locMemento);
+            if (location == null) {
+                // usually because of creation-failure, when not using fail-fast
+                exceptionHandler.onNotFound(BrooklynObjectType.LOCATION, locMemento.getId());
+            } else {
+                try {
+                    ((LocationInternal)location).getRebindSupport().reconstruct(rebindContext, locMemento);
+                } catch (Exception e) {
+                    exceptionHandler.onRebindFailed(BrooklynObjectType.LOCATION, location, e);
+                }
+            }
+        }
+
+        // Reconstruct policies
+        if (rebindManager.persistPoliciesEnabled) {
+            logRebindingDebug("RebindManager reconstructing policies");
+            for (PolicyMemento policyMemento : memento.getPolicyMementos().values()) {
+                Policy policy = rebindContext.getPolicy(policyMemento.getId());
+                logRebindingDebug("RebindManager reconstructing policy {}", policyMemento);
+   
+                if (policy == null) {
+                    // usually because of creation-failure, when not using fail-fast
+                    exceptionHandler.onNotFound(BrooklynObjectType.POLICY, policyMemento.getId());
+                } else {
+                    try {
+                        policy.getRebindSupport().reconstruct(rebindContext, policyMemento);
+                    } catch (Exception e) {
+                        exceptionHandler.onRebindFailed(BrooklynObjectType.POLICY, policy, e);
+                        rebindContext.unregisterPolicy(policy);
+                    }
+                }
+            }
+        }
+
+        // Reconstruct enrichers
+        if (rebindManager.persistEnrichersEnabled) {
+            logRebindingDebug("RebindManager reconstructing enrichers");
+            for (EnricherMemento enricherMemento : memento.getEnricherMementos().values()) {
+                Enricher enricher = rebindContext.getEnricher(enricherMemento.getId());
+                logRebindingDebug("RebindManager reconstructing enricher {}", enricherMemento);
+      
+                if (enricher == null) {
+                    // usually because of creation-failure, when not using fail-fast
+                    exceptionHandler.onNotFound(BrooklynObjectType.ENRICHER, enricherMemento.getId());
+                } else {
+                    try {
+                        enricher.getRebindSupport().reconstruct(rebindContext, enricherMemento);
+                    } catch (Exception e) {
+                        exceptionHandler.onRebindFailed(BrooklynObjectType.ENRICHER, enricher, e);
+                        rebindContext.unregisterEnricher(enricher);
+                    }
+                }
+            }
+        }
+   
+        // Reconstruct feeds
+        if (rebindManager.persistFeedsEnabled) {
+            logRebindingDebug("RebindManager reconstructing feeds");
+            for (FeedMemento feedMemento : memento.getFeedMementos().values()) {
+                Feed feed = rebindContext.getFeed(feedMemento.getId());
+                logRebindingDebug("RebindManager reconstructing feed {}", feedMemento);
+      
+                if (feed == null) {
+                    // usually because of creation-failure, when not using fail-fast
+                    exceptionHandler.onNotFound(BrooklynObjectType.FEED, feedMemento.getId());
+                } else {
+                    try {
+                        feed.getRebindSupport().reconstruct(rebindContext, feedMemento);
+                    } catch (Exception e) {
+                        exceptionHandler.onRebindFailed(BrooklynObjectType.FEED, feed, e);
+                        rebindContext.unregisterFeed(feed);
+                    }
+                }
+
+            }
+        }
+   
+        // Reconstruct entities
+        logRebindingDebug("RebindManager reconstructing entities");
+        for (EntityMemento entityMemento : sortParentFirst(memento.getEntityMementos()).values()) {
+            Entity entity = rebindContext.lookup().lookupEntity(entityMemento.getId());
+            logRebindingDebug("RebindManager reconstructing entity {}", entityMemento);
+   
+            if (entity == null) {
+                // usually because of creation-failure, when not using fail-fast
+                exceptionHandler.onNotFound(BrooklynObjectType.ENTITY, entityMemento.getId());
+            } else {
+                try {
+                    entityMemento.injectTypeClass(entity.getClass());
+                    ((EntityInternal)entity).getRebindSupport().reconstruct(rebindContext, entityMemento);
+                } catch (Exception e) {
+                    exceptionHandler.onRebindFailed(BrooklynObjectType.ENTITY, entity, e);
+                }
+            }
+        }
+    }
+
+    private void associateAdjunctsWithEntities() {
+        
+        checkEnteringPhase(7);
+
+        logRebindingDebug("RebindManager associating adjuncts to entities");
+        for (EntityMemento entityMemento : sortParentFirst(memento.getEntityMementos()).values()) {
+            Entity entity = rebindContext.getEntity(entityMemento.getId());
+            logRebindingDebug("RebindManager associating adjuncts to entity {}", entityMemento);
+   
+            if (entity == null) {
+                // usually because of creation-failure, when not using fail-fast
+                exceptionHandler.onNotFound(BrooklynObjectType.ENTITY, entityMemento.getId());
+            } else {
+                try {
+                    entityMemento.injectTypeClass(entity.getClass());
+                    // TODO these call to the entity which in turn sets the entity on the underlying feeds and enrichers;
+                    // that is taken as the cue to start, but it should not be. start should be a separate call.
+                    ((EntityInternal)entity).getRebindSupport().addPolicies(rebindContext, entityMemento);
+                    ((EntityInternal)entity).getRebindSupport().addEnrichers(rebindContext, entityMemento);
+                    ((EntityInternal)entity).getRebindSupport().addFeeds(rebindContext, entityMemento);
+                } catch (Exception e) {
+                    exceptionHandler.onRebindFailed(BrooklynObjectType.ENTITY, entity, e);
+                }
+            }
+        }
+    }
+
+    private void manageTheObjects() {
+
+        checkEnteringPhase(8);
+        
+        logRebindingDebug("RebindManager managing locations");
+        LocationManagerInternal locationManager = (LocationManagerInternal)managementContext.getLocationManager();
+        Set<String> oldLocations = Sets.newLinkedHashSet(locationManager.getLocationIds());
+        for (Location location: rebindContext.getLocations()) {
+            ManagementTransitionMode oldMode = locationManager.getLastManagementTransitionMode(location.getId());
+            locationManager.setManagementTransitionMode(location, RebindManagerImpl.computeMode(managementContext, location, oldMode, rebindContext.isReadOnly(location)) );
+            if (oldMode!=null)
+                oldLocations.remove(location.getId());
+        }
+        for (Location location: rebindContext.getLocations()) {
+            if (location.getParent()==null) {
+                // manage all root locations
+                try {
+                    ((LocationManagerInternal)managementContext.getLocationManager()).manageRebindedRoot(location);
+                } catch (Exception e) {
+                    exceptionHandler.onManageFailed(BrooklynObjectType.LOCATION, location, e);
+                }
+            }
+        }
+        // destroy old
+        if (!oldLocations.isEmpty()) BrooklynLogging.log(LOG, overwritingMaster ? BrooklynLogging.LoggingLevel.WARN : BrooklynLogging.LoggingLevel.DEBUG, 
+            "Destroying unused locations on rebind: "+oldLocations);
+        for (String oldLocationId: oldLocations) {
+           locationManager.unmanage(locationManager.getLocation(oldLocationId), ManagementTransitionMode.REBINDING_DESTROYED); 
+        }
+        
+        // Manage the top-level apps (causing everything under them to become managed)
+        logRebindingDebug("RebindManager managing entities");
+        EntityManagerInternal entityManager = (EntityManagerInternal)managementContext.getEntityManager();
+        Set<String> oldEntities = Sets.newLinkedHashSet(entityManager.getEntityIds());
+        for (Entity entity: rebindContext.getEntities()) {
+            ManagementTransitionMode oldMode = entityManager.getLastManagementTransitionMode(entity.getId());
+            entityManager.setManagementTransitionMode(entity, RebindManagerImpl.computeMode(managementContext,entity, oldMode, rebindContext.isReadOnly(entity)) );
+            if (oldMode!=null)
+                oldEntities.remove(entity.getId());
+        }
+        List<Application> apps = Lists.newArrayList();
+        for (String appId : memento.getApplicationIds()) {
+            Entity entity = rebindContext.getEntity(appId);
+            if (entity == null) {
+                // usually because of creation-failure, when not using fail-fast
+                exceptionHandler.onNotFound(BrooklynObjectType.ENTITY, appId);
+            } else {
+                try {
+                    entityManager.manageRebindedRoot(entity);
+                } catch (Exception e) {
+                    exceptionHandler.onManageFailed(BrooklynObjectType.ENTITY, entity, e);
+                }
+                apps.add((Application)entity);
+            }
+        }
+        // destroy old
+        if (!oldLocations.isEmpty()) BrooklynLogging.log(LOG, overwritingMaster ? BrooklynLogging.LoggingLevel.WARN : BrooklynLogging.LoggingLevel.DEBUG, 
+            "Destroying unused entities on rebind: "+oldEntities);
+        for (String oldEntityId: oldEntities) {
+           entityManager.unmanage(entityManager.getEntity(oldEntityId), ManagementTransitionMode.REBINDING_DESTROYED); 
+        }
+
+        this.applications = apps;
+    }
+
+    private void finishingUp() {
+        
+        checkContinuingPhase(8);
+        
+        if (!isEmpty) {
+            BrooklynLogging.log(LOG, shouldLogRebinding() ? LoggingLevel.INFO : LoggingLevel.DEBUG, 
+                "Rebind complete " + "("+mode+(readOnlyRebindCount.get()>=0 ? ", iteration "+readOnlyRebindCount : "")+")" +
+                    " in {}: {} app{}, {} entit{}, {} location{}, {} polic{}, {} enricher{}, {} feed{}, {} catalog item{}", new Object[]{
+                Time.makeTimeStringRounded(timer), applications.size(), Strings.s(applications),
+                rebindContext.getEntities().size(), Strings.ies(rebindContext.getEntities()),
+                rebindContext.getLocations().size(), Strings.s(rebindContext.getLocations()),
+                rebindContext.getPolicies().size(), Strings.ies(rebindContext.getPolicies()),
+                rebindContext.getEnrichers().size(), Strings.s(rebindContext.getEnrichers()),
+                rebindContext.getFeeds().size(), Strings.s(rebindContext.getFeeds()),
+                rebindContext.getCatalogItems().size(), Strings.s(rebindContext.getCatalogItems())
+            });
+        }
+
+        // Return the top-level applications
+        logRebindingDebug("RebindManager complete; apps: {}", memento.getApplicationIds());
+    }
+
+    private void noteErrors(final RebindExceptionHandler exceptionHandler, Exception primaryException) {
+        List<Exception> exceptions = exceptionHandler.getExceptions();
+        List<String> warnings = exceptionHandler.getWarnings();
+        if (primaryException!=null || !exceptions.isEmpty() || !warnings.isEmpty()) {
+            List<String> messages = MutableList.<String>of();
+            if (primaryException!=null) messages.add(primaryException.toString());
+            for (Exception e: exceptions) messages.add(e.toString());
+            for (String w: warnings) messages.add(w);
+            rebindMetrics.noteError(messages);
+        }
+    }
+    
+    private String findCatalogItemId(ClassLoader cl, Map<String, EntityMementoManifest> entityIdToManifest, EntityMementoManifest entityManifest) {
+        if (entityManifest.getCatalogItemId() != null) {
+            return entityManifest.getCatalogItemId();
+        }
+
+        if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_INFER_CATALOG_ITEM_ON_REBIND)) {
+            //First check if any of the parent entities has a catalogItemId set.
+            EntityMementoManifest ptr = entityManifest;
+            while (ptr != null) {
+                if (ptr.getCatalogItemId() != null) {
+                    CatalogItem<?, ?> catalogItem = CatalogUtils.getCatalogItemOptionalVersion(managementContext, ptr.getCatalogItemId());
+                    if (catalogItem != null) {
+                        return catalogItem.getId();
+                    } else {
+                        //Couldn't find a catalog item with this id, but return it anyway and
+                        //let the caller deal with the error.
+                        return ptr.getCatalogItemId();
+                    }
+                }
+                if (ptr.getParent() != null) {
+                    ptr = entityIdToManifest.get(ptr.getParent());
+                } else {
+                    ptr = null;
+                }
+            }
+
+            //If no parent entity has the catalogItemId set try to match them by the type we are trying to load.
+            //The current convention is to set catalog item IDs to the java type (for both plain java or CAMP plan) they represent.
+            //This will be applicable only the first time the store is rebinded, while the catalog items don't have the default
+            //version appended to their IDs, but then we will have catalogItemId set on entities so not neede further anyways.
+            BrooklynCatalog catalog = managementContext.getCatalog();
+            ptr = entityManifest;
+            while (ptr != null) {
+                CatalogItem<?, ?> catalogItem = catalog.getCatalogItem(ptr.getType(), BrooklynCatalog.DEFAULT_VERSION);
+                if (catalogItem != null) {
+                    LOG.debug("Inferred catalog item ID "+catalogItem.getId()+" for "+entityManifest+" from ancestor "+ptr);
+                    return catalogItem.getId();
+                }
+                if (ptr.getParent() != null) {
+                    ptr = entityIdToManifest.get(ptr.getParent());
+                } else {
+                    ptr = null;
+                }
+            }
+
+            //As a last resort go through all catalog items trying to load the type and use the first that succeeds.
+            //But first check if can be loaded from the default classpath
+            try {
+                cl.loadClass(entityManifest.getType());
+                return null;
+            } catch (ClassNotFoundException e) {
+            }
+
+            for (CatalogItem<?, ?> item : catalog.getCatalogItems()) {
+                BrooklynClassLoadingContext loader = CatalogUtils.newClassLoadingContext(managementContext, item);
+                boolean canLoadClass = loader.tryLoadClass(entityManifest.getType()).isPresent();
+                if (canLoadClass) {
+                    LOG.warn("Missing catalog item for "+entityManifest.getId()+", inferring as "+item.getId()+" because that is able to load the item");
+                    return item.getId();
+                }
+            }
+        }
+        return null;
+    }
+
+    private class BrooklynObjectInstantiator {
+
+        private final ClassLoader classLoader;
+        private final RebindContextImpl rebindContext;
+        private final Reflections reflections;
+        
+        private BrooklynObjectInstantiator(ClassLoader classLoader, RebindContextImpl rebindContext, Reflections reflections) {
+            this.classLoader = classLoader;
+            this.rebindContext = rebindContext;
+            this.reflections = reflections;
+        }
+
+        private Entity newEntity(String entityId, String entityType, String catalogItemId) {
+            Class<? extends Entity> entityClazz = load(Entity.class, entityType, catalogItemId, entityId);
+
+            Entity entity;
+            
+            if (InternalFactory.isNewStyle(entityClazz)) {
+                // Not using entityManager.createEntity(EntitySpec) because don't want init() to be called.
+                // Creates an uninitialized entity, but that has correct id + proxy.
+                InternalEntityFactory entityFactory = managementContext.getEntityFactory();
+                entity = entityFactory.constructEntity(entityClazz, Reflections.getAllInterfaces(entityClazz), entityId);
+
+            } else {
+                LOG.warn("Deprecated rebind of entity without no-arg constructor; this may not be supported in future versions: id="+entityId+"; type="+entityType);
+
+                // There are several possibilities for the constructor; find one that works.
+                // Prefer passing in the flags because required for Application to set the management context
+                // TODO Feels very hacky!
+
+                Map<Object,Object> flags = Maps.newLinkedHashMap();
+                flags.put("id", entityId);
+                if (AbstractApplication.class.isAssignableFrom(entityClazz)) flags.put("mgmt", managementContext);
+
+                // TODO document the multiple sources of flags, and the reason for setting the mgmt context *and* supplying it as the flag
+                // (NB: merge reported conflict as the two things were added separately)
+                entity = (Entity) invokeConstructor(null, entityClazz, new Object[] {flags}, new Object[] {flags, null}, new Object[] {null}, new Object[0]);
+
+                // In case the constructor didn't take the Map arg, then also set it here.
+                // e.g. for top-level app instances such as WebClusterDatabaseExampleApp will (often?) not have
+                // interface + constructor.
+                // TODO On serializing the memento, we should capture which interfaces so can recreate
+                // the proxy+spec (including for apps where there's not an obvious interface).
+                FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", entityId), entity);
+                if (entity instanceof AbstractApplication) {
+                    FlagUtils.setFieldsFromFlags(ImmutableMap.of("mgmt", managementContext), entity);
+                }
+                ((AbstractEntity)entity).setManagementContext(managementContext);
+                managementContext.prePreManage(entity);
+            }
+            
+            setCatalogItemId(entity, catalogItemId);
+            return entity;
+        }
+
+        private void setCatalogItemId(BrooklynObject item, String catalogItemId) {
+            if (catalogItemId!=null) {
+                ((BrooklynObjectInternal)item).setCatalogItemId(catalogItemId);
+            }
+        }
+
+        private <T extends BrooklynObject> Class<? extends T> load(Class<T> bType, Memento memento) {
+            return load(bType, memento.getType(), memento.getCatalogItemId(), memento.getId());
+        }
+        @SuppressWarnings("unchecked")
+        private <T extends BrooklynObject> Class<? extends T> load(Class<T> bType, String jType, String catalogItemId, String contextSuchAsId) {
+            checkNotNull(jType, "Type of %s (%s) must not be null", contextSuchAsId, bType.getSimpleName());
+            if (catalogItemId != null) {
+                BrooklynClassLoadingContext loader = getLoadingContextFromCatalogItemId(catalogItemId, classLoader, rebindContext);
+                return loader.loadClass(jType, bType);
+            } else {
+                // we have previously used reflections; not sure if that's needed?
+                try {
+                    return (Class<T>)reflections.loadClass(jType);
+                } catch (Exception e) {
+                    LOG.warn("Unable to load "+jType+" using reflections; will try standard context");
+                }
+
+                if (BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_INFER_CATALOG_ITEM_ON_REBIND)) {
+                    //Try loading from whichever catalog bundle succeeds.
+                    BrooklynCatalog catalog = managementContext.getCatalog();
+                    for (CatalogItem<?, ?> item : catalog.getCatalogItems()) {
+                        BrooklynClassLoadingContext catalogLoader = CatalogUtils.newClassLoadingContext(managementContext, item);
+                        Maybe<Class<?>> catalogClass = catalogLoader.tryLoadClass(jType);
+                        if (catalogClass.isPresent()) {
+                            return (Class<? extends T>) catalogClass.get();
+                        }
+                    }
+                    throw new IllegalStateException("No catalogItemId specified and can't load class from either classpath of catalog items");
+                } else {
+                    throw new IllegalStateException("No catalogItemId specified and can't load class from classpath");
+                }
+
+            }
+        }
+
+        private BrooklynClassLoadingContext getLoadingContextFromCatalogItemId(String catalogItemId, ClassLoader classLoader, RebindContext rebindContext) {
+            Preconditions.checkNotNull(catalogItemId, "catalogItemId required (should not be null)");
+            CatalogItem<?, ?> catalogItem = rebindContext.lookup().lookupCatalogItem(catalogItemId);
+            if (catalogItem != null) {
+                return CatalogUtils.newClassLoadingContext(managementContext, catalogItem);
+            } else {
+                throw new IllegalStateException("Failed to load catalog item " + catalogItemId + " required for rebinding.");
+            }
+        }
+
+        /**
+         * Constructs a new location, passing to its constructor the location id and all of memento.getFlags().
+         */
+        private Location newLocation(String locationId, String locationType) {
+            Class<? extends Location> locationClazz = reflections.loadClass(locationType, Location.class);
+
+            if (InternalFactory.isNewStyle(locationClazz)) {
+                // Not using loationManager.createLocation(LocationSpec) because don't want init() to be called
+                // TODO Need to rationalise this to move code into methods of InternalLocationFactory.
+                //      But note that we'll change all locations to be entities at some point!
+                // See same code approach used in #newEntity(EntityMemento, Reflections)
+                InternalLocationFactory locationFactory = managementContext.getLocationFactory();
+                Location location = locationFactory.constructLocation(locationClazz);
+                FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", locationId), location);
+                managementContext.prePreManage(location);
+                ((AbstractLocation)location).setManagementContext(managementContext);
+
+                return location;
+            } else {
+                LOG.warn("Deprecated rebind of location without no-arg constructor; this may not be supported in future versions: id="+locationId+"; type="+locationType);
+
+                // There are several possibilities for the constructor; find one that works.
+                // Prefer passing in the flags because required for Application to set the management context
+                // TODO Feels very hacky!
+                Map<String,?> flags = MutableMap.of("id", locationId, "deferConstructionChecks", true);
+
+                return (Location) invokeConstructor(reflections, locationClazz, new Object[] {flags});
+            }
+            // note 'used' config keys get marked in BasicLocationRebindSupport
+        }
+
+        /**
+         * Constructs a new policy, passing to its constructor the policy id and all of memento.getConfig().
+         */
+        private Policy newPolicy(PolicyMemento memento) {
+            String id = memento.getId();
+            Class<? extends Policy> policyClazz = load(Policy.class, memento.getType(), memento.getCatalogItemId(), id);
+            
+            Policy policy;
+            if (InternalFactory.isNewStyle(policyClazz)) {
+                InternalPolicyFactory policyFactory = managementContext.getPolicyFactory();
+                policy = policyFactory.constructPolicy(policyClazz);
+                FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", id), policy);
+                ((AbstractPolicy)policy).setManagementContext(managementContext);
+
+            } else {
+                LOG.warn("Deprecated rebind of policy without no-arg constructor; this may not be supported in future versions: id="+id+"; type="+policyClazz);
+
+                // There are several possibilities for the constructor; find one that works.
+                // Prefer passing in the flags because required for Application to set the management context
+                // TODO Feels very hacky!
+                Map<String, Object> flags = MutableMap.<String, Object>of(
+                    "id", id, 
+                    "deferConstructionChecks", true,
+                    "noConstructionInit", true);
+                flags.putAll(memento.getConfig());
+
+                policy = invokeConstructor(null, policyClazz, new Object[] {flags});
+            }
+            
+            setCatalogItemId(policy, memento.getCatalogItemId());
+            return policy;
+        }
+
+        /**
+         * Constructs a new enricher, passing to its constructor the enricher id and all of memento.getConfig().
+         */
+        private Enricher newEnricher(EnricherMemento memento) {
+            Class<? extends Enricher> enricherClazz = load(Enricher.class, memento);
+            String id = memento.getId();
+
+            Enricher enricher;
+            if (InternalFactory.isNewStyle(enricherClazz)) {
+                InternalPolicyFactory policyFactory = managementContext.getPolicyFactory();
+                enricher = policyFactory.constructEnricher(enricherClazz);
+                FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", id), enricher);
+                ((AbstractEnricher)enricher).setManagementContext(managementContext);
+
+            } else {
+                LOG.warn("Deprecated rebind of enricher without no-arg constructor; this may not be supported in future versions: id="+id+"; type="+enricherClazz);
+
+                // There are several possibilities for the constructor; find one that works.
+                // Prefer passing in the flags because required for Application to set the management context
+                // TODO Feels very hacky!
+                Map<String, Object> flags = MutableMap.<String, Object>of(
+                    "id", id, 
+                    "deferConstructionChecks", true,
+                    "noConstructionInit", true);
+                flags.putAll(memento.getConfig());
+
+                enricher = invokeConstructor(reflections, enricherClazz, new Object[] {flags});
+            }
+            
+            setCatalogItemId(enricher, memento.getCatalogItemId());
+            return enricher;
+        }
+
+        /**
+         * Constructs a new enricher, passing to its constructor the enricher id and all of memento.getConfig().
+         */
+        private Feed newFeed(FeedMemento memento) {
+            Class<? extends Feed> feedClazz = load(Feed.class, memento);
+            String id = memento.getId();
+
+            Feed feed;
+            if (InternalFactory.isNewStyle(feedClazz)) {
+                InternalPolicyFactory policyFactory = managementContext.getPolicyFactory();
+                feed = policyFactory.constructFeed(feedClazz);
+                FlagUtils.setFieldsFromFlags(ImmutableMap.of("id", id), feed);
+                ((AbstractFeed)feed).setManagementContext(managementContext);
+
+            } else {
+                throw new IllegalStateException("rebind of feed without no-arg constructor unsupported: id="+id+"; type="+feedClazz);
+            }
+            
+            setCatalogItemId(feed, memento.getCatalogItemId());
+            return feed;
+        }
+
+        @SuppressWarnings({ "rawtypes" })
+        private CatalogItem<?, ?> newCatalogItem(CatalogItemMemento memento) {
+            String id = memento.getId();
+            // catalog item subtypes are internal to brooklyn, not in osgi
+            String itemType = checkNotNull(memento.getType(), "catalog item type of %s must not be null in memento", id);
+            Class<? extends CatalogItem> clazz = reflections.loadClass(itemType, CatalogItem.class);
+            return invokeConstructor(reflections, clazz, new Object[]{});
+        }
+
+        private <T> T invokeConstructor(Reflections reflections, Class<T> clazz, Object[]... possibleArgs) {
+            for (Object[] args : possibleArgs) {
+                try {
+                    Optional<T> v = Reflections.invokeConstructorWithArgs(clazz, args, true);
+                    if (v.isPresent()) {
+                        return v.get();
+                    }
+                } catch (Exception e) {
+                    throw Exceptions.propagate(e);
+                }
+            }
+            throw new IllegalStateException("Cannot instantiate instance of type "+clazz+"; expected constructor signature not found");
+        }
+    }
+
+    protected BrooklynMementoPersister getPersister() {
+        return rebindManager.getPersister();
+    }
+    
+    protected <T extends TreeNode> Map<String, T> sortParentFirst(Map<String, T> nodes) {
+        return RebindManagerImpl.sortParentFirst(nodes);
+    }
+
+    /** logs at debug, except during subsequent read-only rebinds, in which it logs trace */
+    private void logRebindingDebug(String message, Object... args) {
+        if (shouldLogRebinding()) {
+            LOG.debug(message, args);
+        } else {
+            LOG.trace(message, args);
+        }
+    }
+    
+    protected boolean shouldLogRebinding() {
+        return (readOnlyRebindCount.get() < 5) || (readOnlyRebindCount.get()%1000==0);
+    }
+
+}


[09/17] incubator-brooklyn git commit: a few comments in addition to #479

Posted by an...@apache.org.
a few comments in addition to #479


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

Branch: refs/heads/master
Commit: bd9b29256207b22133fe6d2eda22b1da3f060027
Parents: 8f55a6e
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Fri Jan 30 13:59:33 2015 +0000
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:07 2015 +0100

----------------------------------------------------------------------
 .../java/brooklyn/entity/proxy/nginx/NginxController.java   | 1 -
 .../entity/proxy/nginx/NginxTemplateConfigGenerator.java    | 9 +++++++--
 2 files changed, 7 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd9b2925/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxController.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxController.java b/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxController.java
index 1ca17df..d4a7315 100644
--- a/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxController.java
+++ b/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxController.java
@@ -37,7 +37,6 @@ import brooklyn.event.basic.Sensors;
 import brooklyn.util.flags.SetFromFlag;
 
 import com.google.common.collect.ImmutableMap;
-import com.google.common.reflect.TypeToken;
 
 /**
  * An entity that represents an Nginx proxy (e.g. for routing requests to servers in a cluster).

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/bd9b2925/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxTemplateConfigGenerator.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxTemplateConfigGenerator.java b/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxTemplateConfigGenerator.java
index faab7a9..aea735f 100644
--- a/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxTemplateConfigGenerator.java
+++ b/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxTemplateConfigGenerator.java
@@ -33,12 +33,17 @@ import com.google.common.collect.LinkedHashMultimap;
 import com.google.common.collect.Multimap;
 
 /**
- * Processes a FreeMarker template to generate the {@code server.conf} configuration file for an {@link NginxController}.
+ * Processes a FreeMarker template to generate the {@code server.conf} configuration file for an 
+ * {@link NginxController}.
+ * <p>
+ * Note this must be explicitly enabled via {@link NginxController#SERVER_CONF_GENERATOR}.
  */
 public class NginxTemplateConfigGenerator implements NginxConfigFileGenerator {
 
     public static final ConfigKey<String> SERVER_CONF_TEMPLATE_URL = ConfigKeys.newStringConfigKey(
-            "nginx.config.templateUrl", "The server.conf configuration file URL (FreeMarker template)", "classpath://brooklyn/entity/proxy/nginx/server.conf");
+            "nginx.config.templateUrl", "The server.conf configuration file URL (FreeMarker template). "
+                + "Only applies if 'nginx.config.generator' specifies a generator which uses a template.", 
+                "classpath://brooklyn/entity/proxy/nginx/server.conf");
 
     public NginxTemplateConfigGenerator() { }
 


[12/17] incubator-brooklyn git commit: Revert "fix maven javac purity on JDK7"

Posted by an...@apache.org.
Revert "fix maven javac purity on JDK7"

This reverts commit d4ecbe7e7190b504461645ace6c7242c57418e9b.

Oops there was a better fix which I did not commit.


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

Branch: refs/heads/master
Commit: efdb672b21dd2729fdbaa99f5cadcfd586eac949
Parents: 8e9d98a
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Fri Jan 30 13:15:39 2015 +0000
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:07 2015 +0100

----------------------------------------------------------------------
 .../io/brooklyn/camp/spi/AbstractResource.java  | 63 ++++++++++----------
 .../brooklyn/camp/spi/ApplicationComponent.java | 20 +++----
 .../java/io/brooklyn/camp/spi/Assembly.java     | 32 +++++-----
 .../io/brooklyn/camp/spi/AssemblyTemplate.java  | 32 +++++-----
 .../io/brooklyn/camp/spi/PlatformComponent.java | 26 ++++----
 5 files changed, 87 insertions(+), 86 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/efdb672b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
index 9906e2b..036a8d6 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
@@ -18,26 +18,27 @@
  */
 package io.brooklyn.camp.spi;
 
+import io.brooklyn.camp.commontypes.RepresentationSkew;
+
 import java.util.Collections;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
 
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
 import brooklyn.util.collections.MutableMap;
 import brooklyn.util.text.Identifiers;
 import brooklyn.util.time.Time;
-import io.brooklyn.camp.commontypes.RepresentationSkew;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
 
 /** Superclass of CAMP resource implementation objects.
  * Typically used to hold common state of implementation objects
  * and to populate the DTO's used by the REST API.
  * <p>
- * These class instances are typically created using the
- * static {@link #builder()} methods they contain.
+ * These class instances are typically created using the 
+ * static {@link #builder()} methods they contain. 
  * The resulting instances are typically immutable,
  * so where fields can change callers should use a new builder
  * (or update an underlying data store).
@@ -49,7 +50,7 @@ import io.brooklyn.camp.commontypes.RepresentationSkew;
 public class AbstractResource {
 
     public static final String CAMP_TYPE = "Resource";
-
+    
     private String id = Identifiers.makeRandomId(8);
     private String name;
     private String type;
@@ -58,12 +59,12 @@ public class AbstractResource {
     private Date created = Time.dropMilliseconds(new Date());
     private List<String> tags = Collections.emptyList();
     private RepresentationSkew representationSkew;
-
+    
     private Map<String,Object> customAttributes = new MutableMap<String, Object>();
-
+    
     /** Use {@link #builder()} to create */
     protected AbstractResource() {}
-
+    
     // getters
 
     public String getId() {
@@ -93,66 +94,66 @@ public class AbstractResource {
     public Map<String, Object> getCustomAttributes() {
         return ImmutableMap.copyOf(customAttributes);
     }
-
+    
     // setters
 
-    void setId(String id) {
+    private void setId(String id) {
         this.id = id;
     }
-    void setName(String name) {
+    private void setName(String name) {
         this.name = name;
     }
-    void setDescription(String description) {
+    private void setDescription(String description) {
         this.description = description;
     }
-    void setSourceCode(String sourceCode) {
+    private void setSourceCode(String sourceCode) {
         this.sourceCode = sourceCode;
     }
-    void setCreated(Date created) {
+    private void setCreated(Date created) {
         // precision beyond seconds breaks equals check
         this.created = Time.dropMilliseconds(created);
     }
-    void setTags(List<String> tags) {
+    private void setTags(List<String> tags) {
         this.tags = ImmutableList.copyOf(tags);
     }
-    void setType(String type) {
+    private void setType(String type) {
         this.type = type;
     }
-    void setRepresentationSkew(RepresentationSkew representationSkew) {
+    private void setRepresentationSkew(RepresentationSkew representationSkew) {
         this.representationSkew = representationSkew;
     }
-    void setCustomAttribute(String key, Object value) {
+    public void setCustomAttribute(String key, Object value) {
         this.customAttributes.put(key, value);
     }
-
+            
     // builder
     @SuppressWarnings("rawtypes")
     public static Builder<? extends AbstractResource,? extends Builder> builder() {
         return new AbstractResourceBuilder(CAMP_TYPE);
     }
-
+    
     /** Builder creates the instance up front to avoid repetition of fields in the builder;
      * but prevents object leakage until build and prevents changes after build,
      * so effectively immutable.
      * <p>
      * Similarly setters in the class are private so those objects are also typically effectively immutable. */
     public abstract static class Builder<T extends AbstractResource,U extends Builder<T,U>> {
-
+        
         private boolean built = false;
         private String type = null;
         private T instance = null;
-
+        
         protected Builder(String type) {
             this.type = type;
         }
-
+        
         @SuppressWarnings("unchecked")
         protected T createResource() {
             return (T) new AbstractResource();
         }
-
+        
         protected synchronized T instance() {
-            if (built)
+            if (built) 
                 throw new IllegalStateException("Builder instance from "+this+" cannot be access after build");
             if (instance==null) {
                 instance = createResource();
@@ -164,16 +165,16 @@ public class AbstractResource {
         protected void initialize() {
             if (type!=null) type(type);
         }
-
+        
         public synchronized T build() {
             T result = instance();
             built = true;
             return result;
         }
-
+        
         @SuppressWarnings("unchecked")
         protected U thisBuilder() { return (U)this; }
-
+        
         public U type(String x) { instance().setType(x); return thisBuilder(); }
         public U id(String x) { instance().setId(x); return thisBuilder(); }
         public U name(String x) { instance().setName(x); return thisBuilder(); }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/efdb672b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
index de1abba..2d70f9c 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
@@ -32,14 +32,14 @@ public class ApplicationComponent extends AbstractResource {
 
     public static final String CAMP_TYPE = "ApplicationComponent";
     static { assert CAMP_TYPE.equals(ApplicationComponent.class.getSimpleName()); }
-
+    
     /** Use {@link #builder()} to create */
     protected ApplicationComponent() {}
 
     ResourceLookup<ApplicationComponent> applicationComponents;
     ResourceLookup<PlatformComponent> platformComponents;
     String externalManagementUri;
-
+    
     public ResourceLookup<ApplicationComponent> getApplicationComponents() {
         return applicationComponents != null ? applicationComponents : new EmptyResourceLookup<ApplicationComponent>();
     }
@@ -47,26 +47,26 @@ public class ApplicationComponent extends AbstractResource {
         return platformComponents != null ? platformComponents : new EmptyResourceLookup<PlatformComponent>();
     }
 
-    void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
+    private void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
         this.applicationComponents = applicationComponents;
     }
-    void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
+    private void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
         this.platformComponents = platformComponents;
     }
-
+    
     // builder
-
+    
     public static Builder<? extends ApplicationComponent> builder() {
         return new Builder<ApplicationComponent>(CAMP_TYPE);
     }
-
+    
     public static class Builder<T extends ApplicationComponent> extends AbstractResource.Builder<T,Builder<T>> {
-
+        
         protected Builder(String type) { super(type); }
 
         public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { instance().setApplicationComponents(x); return thisBuilder(); }
         public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { instance().setPlatformComponents(x); return thisBuilder(); }
-
+        
         public synchronized Builder<T> add(ApplicationComponent x) {
             if (instance().applicationComponents==null) {
                 instance().applicationComponents = new BasicResourceLookup<ApplicationComponent>();
@@ -77,7 +77,7 @@ public class ApplicationComponent extends AbstractResource {
             ((BasicResourceLookup<ApplicationComponent>)instance().applicationComponents).add(x);
             return thisBuilder();
         }
-
+        
         public synchronized Builder<T> add(PlatformComponent x) {
             if (instance().platformComponents==null) {
                 instance().platformComponents = new BasicResourceLookup<PlatformComponent>();

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/efdb672b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
index 90511a2..991f704 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
@@ -32,18 +32,18 @@ public class Assembly extends AbstractResource {
 
     public static final String CAMP_TYPE = "Assembly";
     static { assert CAMP_TYPE.equals(Assembly.class.getSimpleName()); }
-
+    
     /** Use {@link #builder()} to create */
     protected Assembly() {}
 
     AssemblyTemplate assemblyTemplate;
     ResourceLookup<ApplicationComponent> applicationComponents;
     ResourceLookup<PlatformComponent> platformComponents;
-
+    
     // TODO
 //    "parameterDefinitionUri": URI,
 //    "pdpUri" : URI ?
-
+                    
     public AssemblyTemplate getAssemblyTemplate() {
         return assemblyTemplate;
     }
@@ -53,34 +53,34 @@ public class Assembly extends AbstractResource {
     public ResourceLookup<PlatformComponent> getPlatformComponents() {
         return platformComponents != null ? platformComponents : new EmptyResourceLookup<PlatformComponent>();
     }
-
-    void setAssemblyTemplate(AssemblyTemplate assemblyTemplate) {
+    
+    private void setAssemblyTemplate(AssemblyTemplate assemblyTemplate) {
         this.assemblyTemplate = assemblyTemplate;
     }
-    void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
+    private void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
         this.applicationComponents = applicationComponents;
     }
-    void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
+    private void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
         this.platformComponents = platformComponents;
     }
-
+    
     // builder
-
+    
     public static Builder<? extends Assembly> builder() {
         return new Builder<Assembly>(CAMP_TYPE);
     }
-
+    
     public static class Builder<T extends Assembly> extends AbstractResource.Builder<T,Builder<T>> {
-
+        
         protected Builder(String type) { super(type); }
-
+        
         @SuppressWarnings("unchecked")
         protected T createResource() { return (T) new Assembly(); }
-
+        
         public Builder<T> assemblyTemplate(AssemblyTemplate x) { instance().setAssemblyTemplate(x); return thisBuilder(); }
         public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { instance().setApplicationComponents(x); return thisBuilder(); }
         public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { instance().setPlatformComponents(x); return thisBuilder(); }
-
+        
         public synchronized Builder<T> add(ApplicationComponent x) {
             if (instance().applicationComponents==null) {
                 instance().applicationComponents = new BasicResourceLookup<ApplicationComponent>();
@@ -91,7 +91,7 @@ public class Assembly extends AbstractResource {
             ((BasicResourceLookup<ApplicationComponent>)instance().applicationComponents).add(x);
             return thisBuilder();
         }
-
+        
         public synchronized Builder<T> add(PlatformComponent x) {
             if (instance().platformComponents==null) {
                 instance().platformComponents = new BasicResourceLookup<PlatformComponent>();
@@ -102,7 +102,7 @@ public class Assembly extends AbstractResource {
             ((BasicResourceLookup<PlatformComponent>)instance().platformComponents).add(x);
             return thisBuilder();
         }
-
+        
         @Override
         public synchronized T build() {
             return super.build();

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/efdb672b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
index 6a78a55..c308b87 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
@@ -35,15 +35,15 @@ public class AssemblyTemplate extends AbstractResource {
 
     public static final String CAMP_TYPE = "AssemblyTemplate";
     static { assert CAMP_TYPE.equals(AssemblyTemplate.class.getSimpleName()); }
-
+    
     Class<? extends AssemblyTemplateInstantiator> instantiator;
     ResourceLookup<ApplicationComponentTemplate> applicationComponentTemplates;
     ResourceLookup<PlatformComponentTemplate> platformComponentTemplates;
-
+    
     // TODO
 //    "parameterDefinitionUri": URI,
 //    "pdpUri" : URI ?
-
+                    
     /** Use {@link #builder()} to create */
     protected AssemblyTemplate() {}
 
@@ -56,30 +56,30 @@ public class AssemblyTemplate extends AbstractResource {
     public ResourceLookup<PlatformComponentTemplate> getPlatformComponentTemplates() {
         return platformComponentTemplates != null ? platformComponentTemplates : new EmptyResourceLookup<PlatformComponentTemplate>();
     }
-
-    void setInstantiator(Class<? extends AssemblyTemplateInstantiator> instantiator) {
+    
+    private void setInstantiator(Class<? extends AssemblyTemplateInstantiator> instantiator) {
         this.instantiator = instantiator;
     }
-    void setApplicationComponentTemplates(ResourceLookup<ApplicationComponentTemplate> applicationComponentTemplates) {
+    private void setApplicationComponentTemplates(ResourceLookup<ApplicationComponentTemplate> applicationComponentTemplates) {
         this.applicationComponentTemplates = applicationComponentTemplates;
     }
-    void setPlatformComponentTemplates(ResourceLookup<PlatformComponentTemplate> platformComponentTemplates) {
+    private void setPlatformComponentTemplates(ResourceLookup<PlatformComponentTemplate> platformComponentTemplates) {
         this.platformComponentTemplates = platformComponentTemplates;
     }
-
+    
     // builder
-
+    
     public static Builder<? extends AssemblyTemplate> builder() {
         return new Builder<AssemblyTemplate>(CAMP_TYPE);
     }
-
+    
     public static class Builder<T extends AssemblyTemplate> extends AbstractResource.Builder<T,Builder<T>> {
-
+        
         protected Builder(String type) { super(type); }
-
+        
         @SuppressWarnings("unchecked")
         protected T createResource() { return (T) new AssemblyTemplate(); }
-
+        
         public Builder<T> instantiator(Class<? extends AssemblyTemplateInstantiator> x) { instance().setInstantiator(x); return thisBuilder(); }
         public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponentTemplate> x) { instance().setApplicationComponentTemplates(x); return thisBuilder(); }
         public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponentTemplate> x) { instance().setPlatformComponentTemplates(x); return thisBuilder(); }
@@ -87,7 +87,7 @@ public class AssemblyTemplate extends AbstractResource {
         /** allows callers to see the partially formed instance when needed, for example to query instantiators;
          *  could be replaced by specific methods as and when that is preferred */
         public T peek() { return instance(); }
-
+        
         public synchronized Builder<T> add(ApplicationComponentTemplate x) {
             if (instance().applicationComponentTemplates==null) {
                 instance().applicationComponentTemplates = new BasicResourceLookup<ApplicationComponentTemplate>();
@@ -98,7 +98,7 @@ public class AssemblyTemplate extends AbstractResource {
             ((BasicResourceLookup<ApplicationComponentTemplate>)instance().applicationComponentTemplates).add(x);
             return thisBuilder();
         }
-
+        
         public synchronized Builder<T> add(PlatformComponentTemplate x) {
             if (instance().platformComponentTemplates==null) {
                 instance().platformComponentTemplates = new BasicResourceLookup<PlatformComponentTemplate>();
@@ -109,7 +109,7 @@ public class AssemblyTemplate extends AbstractResource {
             ((BasicResourceLookup<PlatformComponentTemplate>)instance().platformComponentTemplates).add(x);
             return thisBuilder();
         }
-
+        
         @Override
         public synchronized T build() {
             Preconditions.checkNotNull(instance().instantiator);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/efdb672b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
index a5c343a..3e3363b 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
@@ -32,14 +32,14 @@ public class PlatformComponent extends AbstractResource {
 
     public static final String CAMP_TYPE = "PlatformComponent";
     static { assert CAMP_TYPE.equals(PlatformComponent.class.getSimpleName()); }
-
+    
     /** Use {@link #builder()} to create */
     protected PlatformComponent() {}
 
     ResourceLookup<ApplicationComponent> applicationComponents;
     ResourceLookup<PlatformComponent> platformComponents;
     String externalManagementUri;
-
+    
     public ResourceLookup<ApplicationComponent> getApplicationComponents() {
         return applicationComponents != null ? applicationComponents : new EmptyResourceLookup<ApplicationComponent>();
     }
@@ -47,34 +47,34 @@ public class PlatformComponent extends AbstractResource {
         return platformComponents != null ? platformComponents : new EmptyResourceLookup<PlatformComponent>();
     }
 
-    void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
+    private void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
         this.applicationComponents = applicationComponents;
     }
-    void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
+    private void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
         this.platformComponents = platformComponents;
     }
-
+    
     public String getExternalManagementUri() {
         return externalManagementUri;
     }
-    void setExternalManagementUri(String externalManagementUri) {
+    private void setExternalManagementUri(String externalManagementUri) {
         this.externalManagementUri = externalManagementUri;
     }
-
+    
     // builder
-
+    
     public static Builder<? extends PlatformComponent> builder() {
         return new Builder<PlatformComponent>(CAMP_TYPE);
     }
-
+    
     public static class Builder<T extends PlatformComponent> extends AbstractResource.Builder<T,Builder<T>> {
-
+        
         protected Builder(String type) { super(type); }
-
+        
         public Builder<T> externalManagementUri(String x) { instance().setExternalManagementUri(x); return thisBuilder(); }
         public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { instance().setApplicationComponents(x); return thisBuilder(); }
         public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { instance().setPlatformComponents(x); return thisBuilder(); }
-
+        
         public synchronized Builder<T> add(ApplicationComponent x) {
             if (instance().applicationComponents==null) {
                 instance().applicationComponents = new BasicResourceLookup<ApplicationComponent>();
@@ -85,7 +85,7 @@ public class PlatformComponent extends AbstractResource {
             ((BasicResourceLookup<ApplicationComponent>)instance().applicationComponents).add(x);
             return thisBuilder();
         }
-
+        
         public synchronized Builder<T> add(PlatformComponent x) {
             if (instance().platformComponents==null) {
                 instance().platformComponents = new BasicResourceLookup<PlatformComponent>();


[03/17] incubator-brooklyn git commit: add some low-level xslt compound transformer rules

Posted by an...@apache.org.
add some low-level xslt compound transformer rules

this will allow refactoring and simplifying the existing mechanisms, and supporting new things like replacing catalogItemId


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

Branch: refs/heads/master
Commit: 7cd66834d331e9f3e7bf908c207f7f0caf215755
Parents: 55b5f65
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Wed Jan 28 12:25:00 2015 +0000
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:06 2015 +0100

----------------------------------------------------------------------
 .../rebind/transformer/CompoundTransformer.java | 106 ++++++++++++++-----
 .../transformer/impl/XsltTransformer.java       |   6 +-
 .../recursiveCopyWithExtraRules.xslt            |  32 ++++++
 .../rebind/transformer/xmlReplaceItem.xslt      |  32 ++++++
 .../transformer/CompoundTransformerTest.java    |  81 +++++++++++++-
 5 files changed, 225 insertions(+), 32 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/7cd66834/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java b/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
index 80cc1ca..7d1c7c8 100644
--- a/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
+++ b/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
@@ -30,6 +30,7 @@ import brooklyn.entity.rebind.transformer.impl.XsltTransformer;
 import brooklyn.mementos.BrooklynMementoRawData;
 import brooklyn.util.ResourceUtils;
 import brooklyn.util.collections.MutableMap;
+import brooklyn.util.text.Strings;
 import brooklyn.util.text.TemplateProcessor;
 
 import com.google.common.annotations.Beta;
@@ -64,34 +65,7 @@ public class CompoundTransformer {
             rawDataTransformers.put(checkNotNull(type, "type"), checkNotNull(val, "val"));
             return this;
         }
-        public Builder renameType(String oldVal, String newVal) {
-            // xstream format for inner classes is like <brooklyn.entity.rebind.transformer.CompoundTransformerTest_-OrigType>
-            oldVal = toXstreamClassnameFormat(oldVal);
-            newVal = toXstreamClassnameFormat(newVal);
-            
-            String xsltTemplate = ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/renameType.xslt");
-            String xslt = TemplateProcessor.processTemplateContents(xsltTemplate, ImmutableMap.of("old_val", oldVal, "new_val", newVal));
-            return xsltTransformer(xslt);
-        }
-        public Builder renameClass(String oldVal, String newVal) {
-            // xstream format for inner classes is like <brooklyn.entity.rebind.transformer.CompoundTransformerTest_-OrigType>
-            oldVal = toXstreamClassnameFormat(oldVal);
-            newVal = toXstreamClassnameFormat(newVal);
-            
-            String xsltTemplate = ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/renameClass.xslt");
-            String xslt = TemplateProcessor.processTemplateContents(xsltTemplate, ImmutableMap.of("old_val", oldVal, "new_val", newVal));
-            return xsltTransformer(xslt);
-        }
-        public Builder renameField(String clazz, String oldVal, String newVal) {
-            // xstream format for inner classes is like <brooklyn.entity.rebind.transformer.CompoundTransformerTest_-OrigType>
-            clazz = toXstreamClassnameFormat(clazz);
-            oldVal = toXstreamClassnameFormat(oldVal);
-            newVal = toXstreamClassnameFormat(newVal);
-            
-            String xsltTemplate = ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/renameField.xslt");
-            String xslt = TemplateProcessor.processTemplateContents(xsltTemplate, ImmutableMap.of("class_name", clazz, "old_val", oldVal, "new_val", newVal));
-            return xsltTransformer(xslt);
-        }
+
         /** registers the given XSLT code to be applied to all persisted {@link BrooklynObjectType}s */
         public Builder xsltTransformer(String xslt) {
             XsltTransformer xsltTransformer = new XsltTransformer(xslt);
@@ -106,7 +80,83 @@ public class CompoundTransformer {
             rawDataTransformer(type, xsltTransformer);
             return this;
         }
+        protected Builder xsltTransformerFromXsltFreemarkerTemplateUrl(String templateUrl, Map<String,String> vars) {
+            String xsltTemplate = ResourceUtils.create(this).getResourceAsString(templateUrl);
+            String xslt = TemplateProcessor.processTemplateContents(xsltTemplate, vars);
+            return xsltTransformer(xslt);
+        }
+        protected Builder xsltTransformerRecursiveCopyWithExtraRules(String ...rules) {
+            String xsltTemplate = ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/recursiveCopyWithExtraRules.xslt");
+            String xslt = TemplateProcessor.processTemplateContents(xsltTemplate, ImmutableMap.of("extra_rules", Strings.join(rules, "\n")));
+            return xsltTransformer(xslt);
+        }
+
+        /** Discards and replaces the item at the given XPath.
+         * <p>
+         * For example to replace all occurrences 
+         * of text "foo" inside a tag "Tag1", you can use <code>TagName/text()[.='foo']</code>;
+         * passing <code>bar</code> as the second argument would cause 
+         * <code>&lt;Tag1&gt;foo&lt;/Tag1&gt;</code> to become <code>&lt;Tag1&gt;bar&lt;/Tag1&gt;</code>.
+         * <p>
+         * Note that java class names may require conversion prior to invoking this;
+         * see {@link #toXstreamClassnameFormat(String)}. 
+         */
+        // ie TagName/text()[.='foo'] with 'bar' causes <Tag1>foo</Tag1> to <Tag1>bar</Tag1>
+        public Builder xmlReplaceItem(String xpathToMatch, String newValue) {
+            return xsltTransformerFromXsltFreemarkerTemplateUrl("classpath://brooklyn/entity/rebind/transformer/xmlReplaceItem.xslt",
+                ImmutableMap.of("xpath_to_match", xpathToMatch, "new_val", newValue));
+            // alternatively:
+//            return xsltTransformerRecursiveCopyWithExtraRules(
+//                "<xsl:template match=\""+xpathToMatch+"\">"
+//                    + newValue
+//                + "</xsl:template>");
+        }
+        
+        /** 
+         * Replaces a tag, but while continuing to recurse.
+         */
+        public Builder xmlRenameTag(String xpathToMatch, String newValue) {
+            return xsltTransformerRecursiveCopyWithExtraRules(
+              "<xsl:template match=\""+xpathToMatch+"\">"
+                  + "<"+newValue+">"
+                      + "<xsl:apply-templates select=\"@*|node()\" />"
+                  + "</"+newValue+">"
+              + "</xsl:template>");
+            // alternatively:
+//            xmlReplaceItem(xpathToMatch, "<"+newValue+">"+"<xsl:apply-templates select=\"@*|node()\" />"+"</"+newValue+">") 
+        }
+
+        /** Changes the contents inside a "type" tag:
+         * where the contents match the old value, they are changed to the new value.
+         * <p> 
+         * In brooklyn/xstream, a "type" node typically gives the name of a java or catalog type to be used
+         * when creating an instance. */
+        public Builder renameType(String oldVal, String newVal) {
+            return xsltTransformerFromXsltFreemarkerTemplateUrl("classpath://brooklyn/entity/rebind/transformer/renameType.xslt",
+                ImmutableMap.of("old_val", toXstreamClassnameFormat(oldVal), "new_val", toXstreamClassnameFormat(newVal)));
+        }
+        /** Changes an XML tag matching a given old value:
+         * the tag is changed to the new value.
+         * <p>
+         * In xstream many tags correspond to the java class of an object so this is a way to change 
+         * the java class (or xstream alias) of a persisted instance (or instance inside them). */
+        public Builder renameClass(String oldVal, String newVal) {
+            return xsltTransformerFromXsltFreemarkerTemplateUrl("classpath://brooklyn/entity/rebind/transformer/renameClass.xslt",
+                ImmutableMap.of("old_val", toXstreamClassnameFormat(oldVal), "new_val", toXstreamClassnameFormat(newVal)));
+        }
+        /** Changes an XML tag inside another tag: 
+         * where the outer tag and inner tag match the values given here,
+         * the inner tag is changed to the new value.
+         * <p>
+         * In stream tags corresponding to fields are contained in the tag corresponding to the class name,
+         * so this gives a way to change the name of a field which will be deserialized. */
+        public Builder renameField(String clazz, String oldVal, String newVal) {
+            return xsltTransformerFromXsltFreemarkerTemplateUrl("classpath://brooklyn/entity/rebind/transformer/renameField.xslt",
+                ImmutableMap.of("class_name", toXstreamClassnameFormat(clazz), "old_val", toXstreamClassnameFormat(oldVal), "new_val", toXstreamClassnameFormat(newVal)));
+        }
+
         private String toXstreamClassnameFormat(String val) {
+            // xstream format for inner classes is like <brooklyn.entity.rebind.transformer.CompoundTransformerTest_-OrigType>
             return (val.contains("$")) ? val.replace("$", "_-") : val;
         }
         public CompoundTransformer build() {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/7cd66834/core/src/main/java/brooklyn/entity/rebind/transformer/impl/XsltTransformer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/transformer/impl/XsltTransformer.java b/core/src/main/java/brooklyn/entity/rebind/transformer/impl/XsltTransformer.java
index feed847..00dfc7f 100644
--- a/core/src/main/java/brooklyn/entity/rebind/transformer/impl/XsltTransformer.java
+++ b/core/src/main/java/brooklyn/entity/rebind/transformer/impl/XsltTransformer.java
@@ -38,14 +38,16 @@ import com.google.common.annotations.Beta;
 public class XsltTransformer implements RawDataTransformer {
 
     private final TransformerFactory factory;
-    private final StreamSource xslt;
+    private final String xsltContent;
 
     public XsltTransformer(String xsltContent) {
         factory = TransformerFactory.newInstance();
-        xslt = new StreamSource(new ByteArrayInputStream(xsltContent.getBytes()));
+        this.xsltContent = xsltContent;
     }
     
     public String transform(String input) throws IOException, URISyntaxException, TransformerException {
+        // stream source is single-use
+        StreamSource xslt = new StreamSource(new ByteArrayInputStream(xsltContent.getBytes()));
         Transformer transformer = factory.newTransformer(xslt);
         
         Source text = new StreamSource(new ByteArrayInputStream(input.getBytes()));

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/7cd66834/core/src/main/resources/brooklyn/entity/rebind/transformer/recursiveCopyWithExtraRules.xslt
----------------------------------------------------------------------
diff --git a/core/src/main/resources/brooklyn/entity/rebind/transformer/recursiveCopyWithExtraRules.xslt b/core/src/main/resources/brooklyn/entity/rebind/transformer/recursiveCopyWithExtraRules.xslt
new file mode 100644
index 0000000..b0f1eb2
--- /dev/null
+++ b/core/src/main/resources/brooklyn/entity/rebind/transformer/recursiveCopyWithExtraRules.xslt
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+    
+     http://www.apache.org/licenses/LICENSE-2.0
+    
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+
+  <xsl:output omit-xml-declaration="yes"/>
+  
+  <xsl:template match="node()|@*">
+    <xsl:copy>
+      <xsl:apply-templates select="node()|@*"/>
+    </xsl:copy>
+  </xsl:template>
+
+${extra_rules}
+
+</xsl:stylesheet>

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/7cd66834/core/src/main/resources/brooklyn/entity/rebind/transformer/xmlReplaceItem.xslt
----------------------------------------------------------------------
diff --git a/core/src/main/resources/brooklyn/entity/rebind/transformer/xmlReplaceItem.xslt b/core/src/main/resources/brooklyn/entity/rebind/transformer/xmlReplaceItem.xslt
new file mode 100644
index 0000000..8d4acc0
--- /dev/null
+++ b/core/src/main/resources/brooklyn/entity/rebind/transformer/xmlReplaceItem.xslt
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+    
+     http://www.apache.org/licenses/LICENSE-2.0
+    
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+
+  <xsl:output omit-xml-declaration="yes"/>
+  
+  <xsl:template match="node()|@*">
+    <xsl:copy>
+      <xsl:apply-templates select="node()|@*"/>
+    </xsl:copy>
+  </xsl:template>
+
+  <xsl:template match="${xpath_to_match}">${new_val}</xsl:template>
+
+</xsl:stylesheet>

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/7cd66834/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java b/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
index c8cc39d..6e7ab36 100644
--- a/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
+++ b/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
@@ -27,16 +27,18 @@ import javax.annotation.Nullable;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.Test;
 
 import brooklyn.config.ConfigKey;
 import brooklyn.entity.Entity;
+import brooklyn.entity.rebind.BrooklynObjectType;
 import brooklyn.entity.rebind.PersistenceExceptionHandler;
 import brooklyn.entity.rebind.PersistenceExceptionHandlerImpl;
 import brooklyn.entity.rebind.RebindExceptionHandler;
-import brooklyn.entity.rebind.RebindOptions;
 import brooklyn.entity.rebind.RebindManager.RebindFailureMode;
+import brooklyn.entity.rebind.RebindOptions;
 import brooklyn.entity.rebind.RebindTestFixtureWithApp;
 import brooklyn.entity.rebind.RebindTestUtils;
 import brooklyn.entity.rebind.RecordingRebindExceptionHandler;
@@ -46,7 +48,6 @@ import brooklyn.entity.rebind.persister.PersistMode;
 import brooklyn.event.basic.BasicConfigKey;
 import brooklyn.management.ManagementContext;
 import brooklyn.management.ha.HighAvailabilityMode;
-import brooklyn.management.internal.LocalManagementContext;
 import brooklyn.management.internal.ManagementContextInternal;
 import brooklyn.mementos.BrooklynMementoRawData;
 import brooklyn.test.entity.TestApplication;
@@ -55,6 +56,7 @@ import brooklyn.util.os.Os;
 
 import com.google.common.base.Objects;
 import com.google.common.base.Predicate;
+import com.google.common.collect.Iterables;
 
 @SuppressWarnings("serial")
 public class CompoundTransformerTest extends RebindTestFixtureWithApp {
@@ -71,6 +73,81 @@ public class CompoundTransformerTest extends RebindTestFixtureWithApp {
     }
 
     @Test
+    public void testXmlReplaceItemText() throws Exception {
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .xmlReplaceItem("Tag1/text()[.='foo']", "bar")
+            .build();
+        assertSingleXmlTransformation(transformer, "<Tag1>foo</Tag1>", "<Tag1>bar</Tag1>");
+        assertSingleXmlTransformation(transformer, "<Tag1>baz</Tag1>", "<Tag1>baz</Tag1>");
+        assertSingleXmlTransformation(transformer, "<Tag2>foo</Tag2>", "<Tag2>foo</Tag2>");
+        // works when nested
+        assertSingleXmlTransformation(transformer, "<Tag0><Tag1>foo</Tag1><Tag2/></Tag0>", "<Tag0><Tag1>bar</Tag1><Tag2/></Tag0>");
+        // keeps attributes and other children
+        assertSingleXmlTransformation(transformer, "<Tag1 attr=\"value\">foo</Tag1>", "<Tag1 attr=\"value\">bar</Tag1>");
+        assertSingleXmlTransformation(transformer, "<Tag1>foo<Tag2/></Tag1>", "<Tag1>bar<Tag2/></Tag1>");
+    }
+    
+    @Test
+    public void testXmlReplaceItemTree() throws Exception {
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .xmlReplaceItem("Tag1[text()='foo']", "<Tag1>bar</Tag1>")
+            .build();
+        assertSingleXmlTransformation(transformer, "<Tag1>foo</Tag1>", "<Tag1>bar</Tag1>");
+        assertSingleXmlTransformation(transformer, "<Tag1>baz</Tag1>", "<Tag1>baz</Tag1>");
+        assertSingleXmlTransformation(transformer, "<Tag2>foo</Tag2>", "<Tag2>foo</Tag2>");
+        // works when nested
+        assertSingleXmlTransformation(transformer, "<Tag0><Tag1>foo</Tag1><Tag2/></Tag0>", "<Tag0><Tag1>bar</Tag1><Tag2/></Tag0>");
+        // this deletes attributes and other children
+        assertSingleXmlTransformation(transformer, "<Tag1 attr=\"value\">foo</Tag1>", "<Tag1>bar</Tag1>");
+        assertSingleXmlTransformation(transformer, "<Tag1>foo<Tag2/></Tag1>", "<Tag1>bar</Tag1>");
+    }
+    
+    @Test
+    public void testXmlReplaceItemAttribute() throws Exception {
+        // note, the syntax for changing an attribute value is obscure, especially the RHS
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .xmlReplaceItem("Tag1/@attr[.='foo']", "<xsl:attribute name=\"attr\">bar</xsl:attribute>")
+            .build();
+        assertSingleXmlTransformation(transformer, "<Tag1 attr=\"foo\">foo</Tag1>", "<Tag1 attr=\"bar\">foo</Tag1>");
+        assertSingleXmlTransformation(transformer, "<Tag1 attr=\"baz\">foo</Tag1>", "<Tag1 attr=\"baz\">foo</Tag1>");
+    }
+    
+    @Test
+    public void testXmlRenameTag() throws Exception {
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .xmlRenameTag("Tag1[text()='foo']", "Tag2")
+            .build();
+        assertSingleXmlTransformation(transformer, "<Tag1>foo</Tag1>", "<Tag2>foo</Tag2>");
+        assertSingleXmlTransformation(transformer, "<Tag1>baz</Tag1>", "<Tag1>baz</Tag1>");
+        assertSingleXmlTransformation(transformer, "<Tag2>foo</Tag2>", "<Tag2>foo</Tag2>");
+        // works when nested
+        assertSingleXmlTransformation(transformer, "<Tag0><Tag1>foo</Tag1><Tag2/></Tag0>", "<Tag0><Tag2>foo</Tag2><Tag2/></Tag0>");
+        // keeps attributes and other children
+        assertSingleXmlTransformation(transformer, "<Tag1 attr=\"value\">foo</Tag1>", "<Tag2 attr=\"value\">foo</Tag2>");
+        assertSingleXmlTransformation(transformer, "<Tag1>foo<Tag2/></Tag1>", "<Tag2>foo<Tag2/></Tag2>");
+    }
+    
+    @Test
+    public void testXmlReplaceItemActuallyAlsoRenamingTag() throws Exception {
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .xmlReplaceItem("Tag1[text()='foo']", "<Tag2><xsl:apply-templates select=\"@*|node()\" /></Tag2>")
+            .build();
+        assertSingleXmlTransformation(transformer, "<Tag1>foo</Tag1>", "<Tag2>foo</Tag2>");
+        assertSingleXmlTransformation(transformer, "<Tag1>baz</Tag1>", "<Tag1>baz</Tag1>");
+        assertSingleXmlTransformation(transformer, "<Tag2>foo</Tag2>", "<Tag2>foo</Tag2>");
+        // works when nested
+        assertSingleXmlTransformation(transformer, "<Tag0><Tag1>foo</Tag1><Tag2/></Tag0>", "<Tag0><Tag2>foo</Tag2><Tag2/></Tag0>");
+        // keeps attributes and other children
+        assertSingleXmlTransformation(transformer, "<Tag1 attr=\"value\">foo</Tag1>", "<Tag2 attr=\"value\">foo</Tag2>");
+        assertSingleXmlTransformation(transformer, "<Tag1>foo<Tag2/></Tag1>", "<Tag2>foo<Tag2/></Tag2>");
+    }
+    
+    protected void assertSingleXmlTransformation(CompoundTransformer transformer, String xmlIn, String xmlOutExpected) throws Exception {
+        String xmlOutActual = Iterables.getOnlyElement( transformer.getRawDataTransformers().get(BrooklynObjectType.ENTITY) ).transform(xmlIn);
+        Assert.assertEquals(xmlOutActual, xmlOutExpected);
+    }
+    
+    @Test
     public void testNoopTransformation() throws Exception {
         CompoundTransformer transformer = CompoundTransformer.builder()
                 .build();


[06/17] incubator-brooklyn git commit: switch xslt transformation to use clearer java names for the changes

Posted by an...@apache.org.
switch xslt transformation to use clearer java names for the changes


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

Branch: refs/heads/master
Commit: 282b0d865cd4c833e032a6b482190e8ca4ed425a
Parents: 7cd6683
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Wed Jan 28 12:51:07 2015 +0000
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:06 2015 +0100

----------------------------------------------------------------------
 .../rebind/transformer/CompoundTransformer.java |  35 +++----
 .../entity/rebind/transformer/renameClass.xslt  |  35 -------
 .../entity/rebind/transformer/renameField.xslt  |  35 -------
 .../entity/rebind/transformer/renameType.xslt   |  41 --------
 .../rebind/transformer/xmlReplaceItem.xslt      |  32 ------
 .../CompoundTransformerLoaderTest.java          |   2 +-
 .../transformer/CompoundTransformerTest.java    | 105 ++++++++++++++++++-
 .../transformer/impl/XsltTransformerTest.java   |  38 ++++++-
 .../rebind/transformer/impl/renameClass.xslt    |  35 +++++++
 .../rebind/transformer/impl/renameField.xslt    |  35 +++++++
 .../rebind/transformer/impl/renameType.xslt     |  41 ++++++++
 11 files changed, 265 insertions(+), 169 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java b/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
index 7d1c7c8..26f6af5 100644
--- a/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
+++ b/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
@@ -103,27 +103,20 @@ public class CompoundTransformer {
          */
         // ie TagName/text()[.='foo'] with 'bar' causes <Tag1>foo</Tag1> to <Tag1>bar</Tag1>
         public Builder xmlReplaceItem(String xpathToMatch, String newValue) {
-            return xsltTransformerFromXsltFreemarkerTemplateUrl("classpath://brooklyn/entity/rebind/transformer/xmlReplaceItem.xslt",
-                ImmutableMap.of("xpath_to_match", xpathToMatch, "new_val", newValue));
-            // alternatively:
-//            return xsltTransformerRecursiveCopyWithExtraRules(
-//                "<xsl:template match=\""+xpathToMatch+"\">"
-//                    + newValue
-//                + "</xsl:template>");
+            return xsltTransformerRecursiveCopyWithExtraRules(
+                "<xsl:template match=\""+xpathToMatch+"\">"
+                    + newValue
+                + "</xsl:template>");
         }
         
         /** 
          * Replaces a tag, but while continuing to recurse.
          */
         public Builder xmlRenameTag(String xpathToMatch, String newValue) {
-            return xsltTransformerRecursiveCopyWithExtraRules(
-              "<xsl:template match=\""+xpathToMatch+"\">"
-                  + "<"+newValue+">"
-                      + "<xsl:apply-templates select=\"@*|node()\" />"
-                  + "</"+newValue+">"
-              + "</xsl:template>");
-            // alternatively:
-//            xmlReplaceItem(xpathToMatch, "<"+newValue+">"+"<xsl:apply-templates select=\"@*|node()\" />"+"</"+newValue+">") 
+            return xmlReplaceItem(xpathToMatch, 
+                "<"+newValue+">"
+                    + "<xsl:apply-templates select=\"@*|node()\" />"
+                + "</"+newValue+">"); 
         }
 
         /** Changes the contents inside a "type" tag:
@@ -132,8 +125,10 @@ public class CompoundTransformer {
          * In brooklyn/xstream, a "type" node typically gives the name of a java or catalog type to be used
          * when creating an instance. */
         public Builder renameType(String oldVal, String newVal) {
-            return xsltTransformerFromXsltFreemarkerTemplateUrl("classpath://brooklyn/entity/rebind/transformer/renameType.xslt",
-                ImmutableMap.of("old_val", toXstreamClassnameFormat(oldVal), "new_val", toXstreamClassnameFormat(newVal)));
+            return xmlReplaceItem("type/text()[.='"+toXstreamClassnameFormat(oldVal)+"']", toXstreamClassnameFormat(newVal));
+            // previously this did a more complex looping, essentially
+            // <when .=oldVal>newVal</when><otherwise><apply-templates/></otherwise>
+            // but i think these are equivalent
         }
         /** Changes an XML tag matching a given old value:
          * the tag is changed to the new value.
@@ -141,8 +136,7 @@ public class CompoundTransformer {
          * In xstream many tags correspond to the java class of an object so this is a way to change 
          * the java class (or xstream alias) of a persisted instance (or instance inside them). */
         public Builder renameClass(String oldVal, String newVal) {
-            return xsltTransformerFromXsltFreemarkerTemplateUrl("classpath://brooklyn/entity/rebind/transformer/renameClass.xslt",
-                ImmutableMap.of("old_val", toXstreamClassnameFormat(oldVal), "new_val", toXstreamClassnameFormat(newVal)));
+            return xmlRenameTag(toXstreamClassnameFormat(oldVal), toXstreamClassnameFormat(newVal));
         }
         /** Changes an XML tag inside another tag: 
          * where the outer tag and inner tag match the values given here,
@@ -151,8 +145,7 @@ public class CompoundTransformer {
          * In stream tags corresponding to fields are contained in the tag corresponding to the class name,
          * so this gives a way to change the name of a field which will be deserialized. */
         public Builder renameField(String clazz, String oldVal, String newVal) {
-            return xsltTransformerFromXsltFreemarkerTemplateUrl("classpath://brooklyn/entity/rebind/transformer/renameField.xslt",
-                ImmutableMap.of("class_name", toXstreamClassnameFormat(clazz), "old_val", toXstreamClassnameFormat(oldVal), "new_val", toXstreamClassnameFormat(newVal)));
+            return xmlRenameTag(toXstreamClassnameFormat(clazz)+"/"+toXstreamClassnameFormat(oldVal), toXstreamClassnameFormat(newVal));
         }
 
         private String toXstreamClassnameFormat(String val) {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/main/resources/brooklyn/entity/rebind/transformer/renameClass.xslt
----------------------------------------------------------------------
diff --git a/core/src/main/resources/brooklyn/entity/rebind/transformer/renameClass.xslt b/core/src/main/resources/brooklyn/entity/rebind/transformer/renameClass.xslt
deleted file mode 100644
index a0800fd..0000000
--- a/core/src/main/resources/brooklyn/entity/rebind/transformer/renameClass.xslt
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
-    Licensed to the Apache Software Foundation (ASF) under one
-    or more contributor license agreements.  See the NOTICE file
-    distributed with this work for additional information
-    regarding copyright ownership.  The ASF licenses this file
-    to you under the Apache License, Version 2.0 (the
-    "License"); you may not use this file except in compliance
-    with the License.  You may obtain a copy of the License at
-    
-     http://www.apache.org/licenses/LICENSE-2.0
-    
-    Unless required by applicable law or agreed to in writing,
-    software distributed under the License is distributed on an
-    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-    KIND, either express or implied.  See the License for the
-    specific language governing permissions and limitations
-    under the License.
--->
-<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
-
-  <xsl:output omit-xml-declaration="yes"/>
-  
-  <xsl:template match="node()|@*">
-    <xsl:copy>
-      <xsl:apply-templates select="node()|@*"/>
-    </xsl:copy>
-  </xsl:template>
-
-  <xsl:template match="${old_val}">
-    <${new_val}><xsl:apply-templates select="@*|node()" /></${new_val}>
-  </xsl:template>
-
-</xsl:stylesheet>
-

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/main/resources/brooklyn/entity/rebind/transformer/renameField.xslt
----------------------------------------------------------------------
diff --git a/core/src/main/resources/brooklyn/entity/rebind/transformer/renameField.xslt b/core/src/main/resources/brooklyn/entity/rebind/transformer/renameField.xslt
deleted file mode 100644
index d4b3354..0000000
--- a/core/src/main/resources/brooklyn/entity/rebind/transformer/renameField.xslt
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
-    Licensed to the Apache Software Foundation (ASF) under one
-    or more contributor license agreements.  See the NOTICE file
-    distributed with this work for additional information
-    regarding copyright ownership.  The ASF licenses this file
-    to you under the Apache License, Version 2.0 (the
-    "License"); you may not use this file except in compliance
-    with the License.  You may obtain a copy of the License at
-    
-     http://www.apache.org/licenses/LICENSE-2.0
-    
-    Unless required by applicable law or agreed to in writing,
-    software distributed under the License is distributed on an
-    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-    KIND, either express or implied.  See the License for the
-    specific language governing permissions and limitations
-    under the License.
--->
-<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
-
-  <xsl:output omit-xml-declaration="yes"/>
-  
-  <xsl:template match="node()|@*">
-    <xsl:copy>
-      <xsl:apply-templates select="node()|@*"/>
-    </xsl:copy>
-  </xsl:template>
-
-  <xsl:template match="${class_name}/${old_val}">
-    <${new_val}><xsl:apply-templates select="@*|node()" /></${new_val}>
-  </xsl:template>
-
-</xsl:stylesheet>
-

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/main/resources/brooklyn/entity/rebind/transformer/renameType.xslt
----------------------------------------------------------------------
diff --git a/core/src/main/resources/brooklyn/entity/rebind/transformer/renameType.xslt b/core/src/main/resources/brooklyn/entity/rebind/transformer/renameType.xslt
deleted file mode 100644
index e53fe37..0000000
--- a/core/src/main/resources/brooklyn/entity/rebind/transformer/renameType.xslt
+++ /dev/null
@@ -1,41 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
-    Licensed to the Apache Software Foundation (ASF) under one
-    or more contributor license agreements.  See the NOTICE file
-    distributed with this work for additional information
-    regarding copyright ownership.  The ASF licenses this file
-    to you under the Apache License, Version 2.0 (the
-    "License"); you may not use this file except in compliance
-    with the License.  You may obtain a copy of the License at
-    
-     http://www.apache.org/licenses/LICENSE-2.0
-    
-    Unless required by applicable law or agreed to in writing,
-    software distributed under the License is distributed on an
-    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-    KIND, either express or implied.  See the License for the
-    specific language governing permissions and limitations
-    under the License.
--->
-<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
-
-  <xsl:output omit-xml-declaration="yes"/>
-  
-  <xsl:template match="node()|@*">
-    <xsl:copy>
-      <xsl:apply-templates select="node()|@*"/>
-    </xsl:copy>
-  </xsl:template>
-
-  <xsl:template match="type">
-    <type>
-      <xsl:copy-of select="@*"/>
-      <xsl:choose>
-        <xsl:when test=".='${old_val}'"><xsl:value-of select="'${new_val}'"/></xsl:when>
-        <xsl:otherwise><xsl:value-of select="." /></xsl:otherwise>
-      </xsl:choose>
-    </type>
-  </xsl:template>
-
-</xsl:stylesheet>
-

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/main/resources/brooklyn/entity/rebind/transformer/xmlReplaceItem.xslt
----------------------------------------------------------------------
diff --git a/core/src/main/resources/brooklyn/entity/rebind/transformer/xmlReplaceItem.xslt b/core/src/main/resources/brooklyn/entity/rebind/transformer/xmlReplaceItem.xslt
deleted file mode 100644
index 8d4acc0..0000000
--- a/core/src/main/resources/brooklyn/entity/rebind/transformer/xmlReplaceItem.xslt
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<!--
-    Licensed to the Apache Software Foundation (ASF) under one
-    or more contributor license agreements.  See the NOTICE file
-    distributed with this work for additional information
-    regarding copyright ownership.  The ASF licenses this file
-    to you under the Apache License, Version 2.0 (the
-    "License"); you may not use this file except in compliance
-    with the License.  You may obtain a copy of the License at
-    
-     http://www.apache.org/licenses/LICENSE-2.0
-    
-    Unless required by applicable law or agreed to in writing,
-    software distributed under the License is distributed on an
-    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-    KIND, either express or implied.  See the License for the
-    specific language governing permissions and limitations
-    under the License.
--->
-<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
-
-  <xsl:output omit-xml-declaration="yes"/>
-  
-  <xsl:template match="node()|@*">
-    <xsl:copy>
-      <xsl:apply-templates select="node()|@*"/>
-    </xsl:copy>
-  </xsl:template>
-
-  <xsl:template match="${xpath_to_match}">${new_val}</xsl:template>
-
-</xsl:stylesheet>

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoaderTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoaderTest.java b/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoaderTest.java
index e473245..454e860 100644
--- a/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoaderTest.java
+++ b/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoaderTest.java
@@ -45,7 +45,7 @@ public class CompoundTransformerLoaderTest {
                 "  old_val: myoldname\n"+
                 "  new_val: mynewname\n"+
                 "xslt:\n"+
-                "  url: classpath://brooklyn/entity/rebind/transformer/renameType.xslt\n"+
+                "  url: classpath://brooklyn/entity/rebind/transformer/impl/renameType.xslt\n"+
                 "  substitutions:\n"+
                 "    old_val: myoldname\n"+
                 "    new_val: mynewname\n"+

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java b/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
index 6e7ab36..49c1005 100644
--- a/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
+++ b/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
@@ -62,7 +62,8 @@ import com.google.common.collect.Iterables;
 public class CompoundTransformerTest extends RebindTestFixtureWithApp {
 
     private static final Logger LOG = LoggerFactory.getLogger(CompoundTransformerTest.class);
-
+    private static String NEWLINE = Os.LINE_SEPARATOR;
+    
     private File newMementoDir;
     
     @AfterMethod(alwaysRun=true)
@@ -192,6 +193,108 @@ public class CompoundTransformerTest extends RebindTestFixtureWithApp {
         assertTrue(newPredicate.apply(newApp));
     }
     
+    @Test
+    public void testRenameTypeInXml() throws Exception {
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .renameType("mytype.Before", "mytype.After")
+            .build();
+        
+        String input = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <type myattrib2=\"myval2\">mytype.Before</type>"+NEWLINE+
+                "  <nested>"+NEWLINE+
+                "    <type myattrib3=\"myval3\">doesNotMatch</type>"+NEWLINE+
+                "    <type myattrib4=\"myval4\">partial.mytype.Before</type>"+NEWLINE+
+                "    <type myattrib5=\"myval5\">mytype.Before</type>"+NEWLINE+
+                "  </nested>"+NEWLINE+
+                "  <id>myid</id>"+NEWLINE+
+                "</entity>";
+        String expected = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <type myattrib2=\"myval2\">mytype.After</type>"+NEWLINE+
+                "  <nested>"+NEWLINE+
+                "    <type myattrib3=\"myval3\">doesNotMatch</type>"+NEWLINE+
+                "    <type myattrib4=\"myval4\">partial.mytype.Before</type>"+NEWLINE+
+                "    <type myattrib5=\"myval5\">mytype.After</type>"+NEWLINE+
+                "  </nested>"+NEWLINE+
+                "  <id>myid</id>"+NEWLINE+
+                "</entity>";
+        
+        assertSingleXmlTransformation(transformer, input, expected);
+    }
+    
+    @Test
+    public void testRenameFieldInXml() throws Exception {
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .renameField("MyClass", "myFieldBefore", "myFieldAfter")
+            .build();
+        
+        String input = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <type myattrib2=\"myval2\">mytype.Before</type>"+NEWLINE+
+                "  <config>"+NEWLINE+
+                "    <test.conf1>"+NEWLINE+
+                "      <MyClass>"+NEWLINE+
+                "        <myFieldBefore class=\"string\">myfieldval</myFieldBefore>"+NEWLINE+
+                "      </MyClass>"+NEWLINE+
+                "    </test.conf1>"+NEWLINE+
+                "    <test.conf2>"+NEWLINE+
+                "      <MyOtherClass>"+NEWLINE+
+                "        <myFieldBefore class=\"string\">myfieldval</myFieldBefore>"+NEWLINE+
+                "      </MyOtherClass>"+NEWLINE+
+                "    </test.conf2>"+NEWLINE+
+                "  </config>"+NEWLINE+
+                "</entity>";
+        String expected = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <type myattrib2=\"myval2\">mytype.Before</type>"+NEWLINE+
+                "  <config>"+NEWLINE+
+                "    <test.conf1>"+NEWLINE+
+                "      <MyClass>"+NEWLINE+
+                "        <myFieldAfter class=\"string\">myfieldval</myFieldAfter>"+NEWLINE+
+                "      </MyClass>"+NEWLINE+
+                "    </test.conf1>"+NEWLINE+
+                "    <test.conf2>"+NEWLINE+
+                "      <MyOtherClass>"+NEWLINE+
+                "        <myFieldBefore class=\"string\">myfieldval</myFieldBefore>"+NEWLINE+
+                "      </MyOtherClass>"+NEWLINE+
+                "    </test.conf2>"+NEWLINE+
+                "  </config>"+NEWLINE+
+                "</entity>";
+        
+        assertSingleXmlTransformation(transformer, input, expected);
+    }
+    
+    @Test
+    public void testRenameClassInXml() throws Exception {
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .renameClass("MyClassBefore", "MyClassAfter")
+            .build();
+
+        String input = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <type myattrib2=\"myval2\">mytype.Before</type>"+NEWLINE+
+                "  <config>"+NEWLINE+
+                "    <test.conf1>"+NEWLINE+
+                "      <MyClassBefore>"+NEWLINE+
+                "      </MyClassBefore>"+NEWLINE+
+                "    </test.conf1>"+NEWLINE+
+                "  </config>"+NEWLINE+
+                "</entity>";
+        String expected = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <type myattrib2=\"myval2\">mytype.Before</type>"+NEWLINE+
+                "  <config>"+NEWLINE+
+                "    <test.conf1>"+NEWLINE+
+                "      <MyClassAfter>"+NEWLINE+
+                "      </MyClassAfter>"+NEWLINE+
+                "    </test.conf1>"+NEWLINE+
+                "  </config>"+NEWLINE+
+                "</entity>";
+        
+        assertSingleXmlTransformation(transformer, input, expected);
+    }
+    
     protected TestApplication transformAndRebind(CompoundTransformer transformer) throws Exception {
         RebindTestUtils.waitForPersisted(origApp);
         BrooklynMementoRawData newRawData = transform(origManagementContext, transformer);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/test/java/brooklyn/entity/rebind/transformer/impl/XsltTransformerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/rebind/transformer/impl/XsltTransformerTest.java b/core/src/test/java/brooklyn/entity/rebind/transformer/impl/XsltTransformerTest.java
index cc801b2..5791dd4 100644
--- a/core/src/test/java/brooklyn/entity/rebind/transformer/impl/XsltTransformerTest.java
+++ b/core/src/test/java/brooklyn/entity/rebind/transformer/impl/XsltTransformerTest.java
@@ -28,13 +28,45 @@ import brooklyn.util.text.TemplateProcessor;
 
 import com.google.common.collect.ImmutableMap;
 
+/**
+ * Tests the low-level XSLT transformer logic.
+ * <p>
+ * Some of the tests use xslt files which are no longer used to perform type/class/field-specific changes,
+ * but they are included here because they are still useful test cases for XSLT. 
+ */
 public class XsltTransformerTest {
 
     private static String NEWLINE = Os.LINE_SEPARATOR;
+
+    @Test
+    public void testRecursiveCopyExtraRules() throws Exception {
+        String xsltTemplate = ResourceUtils.create(XsltTransformerTest.class).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/recursiveCopyWithExtraRules.xslt");
+        String xslt = TemplateProcessor.processTemplateContents(xsltTemplate, ImmutableMap.of(
+            "extra_rules", "<xsl:template match=\"nested\"><empty_nest/></xsl:template>"));
+        String input = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <type myattrib2=\"myval2\">mytype</type>"+NEWLINE+
+                "  <nested>"+NEWLINE+
+                "    <type myattrib3=\"myval3\">foo</type>"+NEWLINE+
+                "    bar"+NEWLINE+
+                "  </nested>"+NEWLINE+
+                "  <id>myid</id>"+NEWLINE+
+                "</entity>";
+        String expected = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <type myattrib2=\"myval2\">mytype</type>"+NEWLINE+
+                "  <empty_nest/>"+NEWLINE+
+                "  <id>myid</id>"+NEWLINE+
+                "</entity>";
+        
+        XsltTransformer transformer = new XsltTransformer(xslt);
+        String result = transformer.transform(input);
+        assertEquals(result, expected);
+    }
     
     @Test
     public void testRenameType() throws Exception {
-        String xsltTemplate = ResourceUtils.create(XsltTransformerTest.class).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/renameType.xslt");
+        String xsltTemplate = ResourceUtils.create(XsltTransformerTest.class).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/impl/renameType.xslt");
         String xslt = TemplateProcessor.processTemplateContents(xsltTemplate, ImmutableMap.of("old_val", "mytype.Before", "new_val", "mytype.After"));
         String input = 
                 "<entity myattrib=\"myval\">"+NEWLINE+
@@ -64,7 +96,7 @@ public class XsltTransformerTest {
     
     @Test
     public void testRenameField() throws Exception {
-        String xsltTemplate = ResourceUtils.create(XsltTransformerTest.class).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/renameField.xslt");
+        String xsltTemplate = ResourceUtils.create(XsltTransformerTest.class).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/impl/renameField.xslt");
         String xslt = TemplateProcessor.processTemplateContents(xsltTemplate, ImmutableMap.of("class_name", "MyClass", "old_val", "myFieldBefore", "new_val", "myFieldAfter"));
         String input = 
                 "<entity myattrib=\"myval\">"+NEWLINE+
@@ -106,7 +138,7 @@ public class XsltTransformerTest {
     
     @Test
     public void testRenameClass() throws Exception {
-        String xsltTemplate = ResourceUtils.create(XsltTransformerTest.class).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/renameClass.xslt");
+        String xsltTemplate = ResourceUtils.create(XsltTransformerTest.class).getResourceAsString("classpath://brooklyn/entity/rebind/transformer/impl/renameClass.xslt");
         String xslt = TemplateProcessor.processTemplateContents(xsltTemplate, ImmutableMap.of("old_val", "MyClassBefore", "new_val", "MyClassAfter"));
         String input = 
                 "<entity myattrib=\"myval\">"+NEWLINE+

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameClass.xslt
----------------------------------------------------------------------
diff --git a/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameClass.xslt b/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameClass.xslt
new file mode 100644
index 0000000..a0800fd
--- /dev/null
+++ b/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameClass.xslt
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+    
+     http://www.apache.org/licenses/LICENSE-2.0
+    
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+
+  <xsl:output omit-xml-declaration="yes"/>
+  
+  <xsl:template match="node()|@*">
+    <xsl:copy>
+      <xsl:apply-templates select="node()|@*"/>
+    </xsl:copy>
+  </xsl:template>
+
+  <xsl:template match="${old_val}">
+    <${new_val}><xsl:apply-templates select="@*|node()" /></${new_val}>
+  </xsl:template>
+
+</xsl:stylesheet>
+

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameField.xslt
----------------------------------------------------------------------
diff --git a/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameField.xslt b/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameField.xslt
new file mode 100644
index 0000000..d4b3354
--- /dev/null
+++ b/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameField.xslt
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+    
+     http://www.apache.org/licenses/LICENSE-2.0
+    
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+
+  <xsl:output omit-xml-declaration="yes"/>
+  
+  <xsl:template match="node()|@*">
+    <xsl:copy>
+      <xsl:apply-templates select="node()|@*"/>
+    </xsl:copy>
+  </xsl:template>
+
+  <xsl:template match="${class_name}/${old_val}">
+    <${new_val}><xsl:apply-templates select="@*|node()" /></${new_val}>
+  </xsl:template>
+
+</xsl:stylesheet>
+

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/282b0d86/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameType.xslt
----------------------------------------------------------------------
diff --git a/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameType.xslt b/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameType.xslt
new file mode 100644
index 0000000..e53fe37
--- /dev/null
+++ b/core/src/test/resources/brooklyn/entity/rebind/transformer/impl/renameType.xslt
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+    
+     http://www.apache.org/licenses/LICENSE-2.0
+    
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
+
+  <xsl:output omit-xml-declaration="yes"/>
+  
+  <xsl:template match="node()|@*">
+    <xsl:copy>
+      <xsl:apply-templates select="node()|@*"/>
+    </xsl:copy>
+  </xsl:template>
+
+  <xsl:template match="type">
+    <type>
+      <xsl:copy-of select="@*"/>
+      <xsl:choose>
+        <xsl:when test=".='${old_val}'"><xsl:value-of select="'${new_val}'"/></xsl:when>
+        <xsl:otherwise><xsl:value-of select="." /></xsl:otherwise>
+      </xsl:choose>
+    </type>
+  </xsl:template>
+
+</xsl:stylesheet>
+


[13/17] incubator-brooklyn git commit: Java 8 compile fixes

Posted by an...@apache.org.
Java 8 compile fixes


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

Branch: refs/heads/master
Commit: 23e755c9ce03c54e24ad399b6a6e18733df8e487
Parents: fc41bb9
Author: Svetoslav Neykov <sv...@cloudsoftcorp.com>
Authored: Fri Jan 30 22:59:17 2015 +0200
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:07 2015 +0100

----------------------------------------------------------------------
 .../brooklyn/entity/basic/ExplicitEffector.java |  2 +-
 .../entity/basic/ServiceStateLogic.java         |  4 ++--
 .../event/basic/DependentConfiguration.java     |  4 ++--
 .../nosql/cassandra/CassandraNodeImpl.java      | 20 ++++++++++++--------
 .../entity/osgi/karaf/KarafContainerImpl.java   |  7 ++++++-
 5 files changed, 23 insertions(+), 14 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/23e755c9/core/src/main/java/brooklyn/entity/basic/ExplicitEffector.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/basic/ExplicitEffector.java b/core/src/main/java/brooklyn/entity/basic/ExplicitEffector.java
index d572b92..c8035d0 100644
--- a/core/src/main/java/brooklyn/entity/basic/ExplicitEffector.java
+++ b/core/src/main/java/brooklyn/entity/basic/ExplicitEffector.java
@@ -38,7 +38,7 @@ public abstract class ExplicitEffector<I,T> extends AbstractEffector<T> {
     }
 
     public T call(Entity entity, Map parameters) {
-        return invokeEffector((I) entity, parameters );
+        return invokeEffector((I) entity, (Map<String,?>)parameters );
     }
 
     public abstract T invokeEffector(I trait, Map<String,?> parameters);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/23e755c9/core/src/main/java/brooklyn/entity/basic/ServiceStateLogic.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/basic/ServiceStateLogic.java b/core/src/main/java/brooklyn/entity/basic/ServiceStateLogic.java
index f9a7e2d..d8fc957 100644
--- a/core/src/main/java/brooklyn/entity/basic/ServiceStateLogic.java
+++ b/core/src/main/java/brooklyn/entity/basic/ServiceStateLogic.java
@@ -183,9 +183,9 @@ public class ServiceStateLogic {
         @SuppressWarnings({ "unchecked", "rawtypes" })
         public static final EnricherSpec<?> newEnricherForServiceUpIfNotUpIndicatorsEmpty() {
             return Enrichers.builder()
-                .transforming(SERVICE_NOT_UP_INDICATORS).publishing(Attributes.SERVICE_UP)
+                .transforming(SERVICE_NOT_UP_INDICATORS).<Object>publishing(Attributes.SERVICE_UP)
                 .suppressDuplicates(true)
-                .computing( /* cast hacks to support removing */ (Function)
+                .computing(
                     Functionals.<Map<String,?>>
                         ifNotEquals(null).<Object>apply(Functions.forPredicate(CollectionFunctionals.<String>mapSizeEquals(0)))
                         .defaultValue(Entities.REMOVE) )

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/23e755c9/core/src/main/java/brooklyn/event/basic/DependentConfiguration.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/event/basic/DependentConfiguration.java b/core/src/main/java/brooklyn/event/basic/DependentConfiguration.java
index b1d1526..b462107 100644
--- a/core/src/main/java/brooklyn/event/basic/DependentConfiguration.java
+++ b/core/src/main/java/brooklyn/event/basic/DependentConfiguration.java
@@ -707,7 +707,7 @@ public class DependentConfiguration {
         // if desired, the use of this multiSource could allow different conditions; 
         // but probably an easier API just for the caller to build the parallel task  
         protected final List<AttributeAndSensorCondition<?>> multiSource = Lists.newArrayList();
-        protected Function<? super List<V>, ? extends V2> postProcessFromMultiple;
+        protected Function<? super List<V>, V2> postProcessFromMultiple;
         
         /** returns a task for parallel execution returning a list of values of the given sensor list on the given entity, 
          * optionally when the values satisfy a given readiness predicate (defaulting to groovy truth if not supplied) */ 
@@ -810,7 +810,7 @@ public class DependentConfiguration {
                             List<V> prePostProgress = DynamicTasks.queue(parallelTask).get();
                             return DynamicTasks.queue(
                                 Tasks.<V2>builder().name("post-processing").description("Applying "+postProcessFromMultiple)
-                                    .body(Functionals.<List<V>,V2>callable((Function)postProcessFromMultiple, prePostProgress))
+                                    .body(Functionals.callable(postProcessFromMultiple, prePostProgress))
                                     .build()).get();
                         }
                     })

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/23e755c9/software/nosql/src/main/java/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
----------------------------------------------------------------------
diff --git a/software/nosql/src/main/java/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java b/software/nosql/src/main/java/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
index 3056495..5c7b8fd 100644
--- a/software/nosql/src/main/java/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
+++ b/software/nosql/src/main/java/brooklyn/entity/nosql/cassandra/CassandraNodeImpl.java
@@ -418,9 +418,10 @@ public class CassandraNodeImpl extends SoftwareProcessImpl implements CassandraN
                 .pollAttribute(new JmxAttributePollConfig<Set<BigInteger>>(TOKENS)
                         .objectName(storageServiceMBean)
                         .attributeName("TokenToEndpointMap")
-                        .onSuccess((Function) new Function<Map, Set<BigInteger>>() {
+                        .onSuccess(new Function<Object, Set<BigInteger>>() {
                             @Override
-                            public Set<BigInteger> apply(@Nullable Map input) {
+                            public Set<BigInteger> apply(@Nullable Object arg) {
+                                Map input = (Map)arg;
                                 if (input == null || input.isEmpty()) return null;
                                 // FIXME does not work on aws-ec2, uses RFC1918 address
                                 Predicate<String> self = Predicates.in(ImmutableList.of(getAttribute(HOSTNAME), getAttribute(ADDRESS), getAttribute(SUBNET_ADDRESS), getAttribute(SUBNET_HOSTNAME)));
@@ -435,9 +436,10 @@ public class CassandraNodeImpl extends SoftwareProcessImpl implements CassandraN
                 .pollAttribute(new JmxAttributePollConfig<BigInteger>(TOKEN)
                         .objectName(storageServiceMBean)
                         .attributeName("TokenToEndpointMap")
-                        .onSuccess((Function) new Function<Map, BigInteger>() {
+                        .onSuccess(new Function<Object, BigInteger>() {
                             @Override
-                            public BigInteger apply(@Nullable Map input) {
+                            public BigInteger apply(@Nullable Object arg) {
+                                Map input = (Map)arg;
                                 // TODO remove duplication from setting TOKENS
                                 if (input == null || input.isEmpty()) return null;
                                 // FIXME does not work on aws-ec2, uses RFC1918 address
@@ -462,9 +464,10 @@ public class CassandraNodeImpl extends SoftwareProcessImpl implements CassandraN
                 .pollAttribute(new JmxAttributePollConfig<Integer>(PEERS)
                         .objectName(storageServiceMBean)
                         .attributeName("TokenToEndpointMap")
-                        .onSuccess((Function) new Function<Map, Integer>() {
+                        .onSuccess(new Function<Object, Integer>() {
                             @Override
-                            public Integer apply(@Nullable Map input) {
+                            public Integer apply(@Nullable Object arg) {
+                                Map input = (Map)arg;
                                 if (input == null || input.isEmpty()) return 0;
                                 return input.size();
                             }
@@ -473,9 +476,10 @@ public class CassandraNodeImpl extends SoftwareProcessImpl implements CassandraN
                 .pollAttribute(new JmxAttributePollConfig<Integer>(LIVE_NODE_COUNT)
                         .objectName(storageServiceMBean)
                         .attributeName("LiveNodes")
-                        .onSuccess((Function) new Function<List, Integer>() {
+                        .onSuccess(new Function<Object, Integer>() {
                             @Override
-                            public Integer apply(@Nullable List input) {
+                            public Integer apply(@Nullable Object arg) {
+                                List input = (List)arg;
                                 if (input == null || input.isEmpty()) return 0;
                                 return input.size();
                             }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/23e755c9/software/osgi/src/main/java/brooklyn/entity/osgi/karaf/KarafContainerImpl.java
----------------------------------------------------------------------
diff --git a/software/osgi/src/main/java/brooklyn/entity/osgi/karaf/KarafContainerImpl.java b/software/osgi/src/main/java/brooklyn/entity/osgi/karaf/KarafContainerImpl.java
index 4d48abb..b73fd7f 100644
--- a/software/osgi/src/main/java/brooklyn/entity/osgi/karaf/KarafContainerImpl.java
+++ b/software/osgi/src/main/java/brooklyn/entity/osgi/karaf/KarafContainerImpl.java
@@ -125,7 +125,12 @@ public class KarafContainerImpl extends SoftwareProcessImpl implements KarafCont
                 .pollAttribute(new JmxAttributePollConfig<Map>(KARAF_INSTANCES)
                         .objectName(karafAdminObjectName)
                         .attributeName("Instances")
-                        .onSuccess((Function)JmxValueFunctions.tabularDataToMap())
+                        .onSuccess(new Function<Object, Map>() {
+                            @Override
+                            public Map apply(Object input) {
+                                return JmxValueFunctions.tabularDataToMap((TabularData)input);
+                            }
+                        })
                         .onException(new Function<Exception,Map>() {
                                 @Override public Map apply(Exception input) {
                                     // If MBean is unreachable, then mark as service-down


[02/17] incubator-brooklyn git commit: add low-level transformer support for changing catalogItemId

Posted by an...@apache.org.
add low-level transformer support for changing catalogItemId


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

Branch: refs/heads/master
Commit: 7d6c77c6e1dd12c8acce7bdcfc15cd88d800067a
Parents: 282b0d8
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Wed Jan 28 17:01:55 2015 +0000
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:06 2015 +0100

----------------------------------------------------------------------
 .../rebind/transformer/CompoundTransformer.java | 59 ++++++++++++++-----
 .../transformer/CompoundTransformerLoader.java  | 13 ++++-
 .../CompoundTransformerLoaderTest.java          |  9 ++-
 .../transformer/CompoundTransformerTest.java    | 60 +++++++++++++++++++-
 4 files changed, 125 insertions(+), 16 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/7d6c77c6/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java b/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
index 26f6af5..bb87783 100644
--- a/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
+++ b/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformer.java
@@ -34,10 +34,11 @@ import brooklyn.util.text.Strings;
 import brooklyn.util.text.TemplateProcessor;
 
 import com.google.common.annotations.Beta;
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
 import com.google.common.collect.ArrayListMultimap;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Multimap;
-import com.google.common.annotations.VisibleForTesting;
 
 @Beta
 public class CompoundTransformer {
@@ -119,34 +120,66 @@ public class CompoundTransformer {
                 + "</"+newValue+">"); 
         }
 
-        /** Changes the contents inside a "type" tag:
-         * where the contents match the old value, they are changed to the new value.
+        /** 
+         * Renames an explicit type name reference in brooklyn-xstream serialization.
+         * <p>
+         * Really this changes the contents inside any tag named "type",
+         * where the contents match the oldVal, they are changed to the newVal.
          * <p> 
-         * In brooklyn/xstream, a "type" node typically gives the name of a java or catalog type to be used
-         * when creating an instance. */
+         * In brooklyn-xstream, the "type" node typically gives the name of a java or catalog type to be used
+         * when creating an instance; that's how this works. 
+         */
         public Builder renameType(String oldVal, String newVal) {
             return xmlReplaceItem("type/text()[.='"+toXstreamClassnameFormat(oldVal)+"']", toXstreamClassnameFormat(newVal));
             // previously this did a more complex looping, essentially
             // <when .=oldVal>newVal</when><otherwise><apply-templates/></otherwise>
             // but i think these are equivalent
         }
-        /** Changes an XML tag matching a given old value:
+        /** 
+         * Renames an implicit class name reference (a tag).
+         * <p>
+         * Really this changes any XML tag matching a given old value;
          * the tag is changed to the new value.
          * <p>
-         * In xstream many tags correspond to the java class of an object so this is a way to change 
-         * the java class (or xstream alias) of a persisted instance (or instance inside them). */
+         * In brooklyn-xstream many tags correspond to the java class of an object;
+         * that's how this works to to change the java class (or xstream alias) 
+         * of a persisted instance, included nested instances. 
+         */
         public Builder renameClass(String oldVal, String newVal) {
             return xmlRenameTag(toXstreamClassnameFormat(oldVal), toXstreamClassnameFormat(newVal));
         }
-        /** Changes an XML tag inside another tag: 
-         * where the outer tag and inner tag match the values given here,
-         * the inner tag is changed to the new value.
+        /** 
+         * Renames a field in xstream serialization.
          * <p>
-         * In stream tags corresponding to fields are contained in the tag corresponding to the class name,
-         * so this gives a way to change the name of a field which will be deserialized. */
+         * Really this changes an XML tag inside another tag, 
+         * where the outer tag and inner tag match the clazz and oldVal values given here,
+         * the inner tag is changed to the newVal.
+         * <p>
+         * In brooklyn-xstream, tags corresponding to fields are contained in the tag 
+         * corresponding to the class name; that's how this works.
+         */
         public Builder renameField(String clazz, String oldVal, String newVal) {
             return xmlRenameTag(toXstreamClassnameFormat(clazz)+"/"+toXstreamClassnameFormat(oldVal), toXstreamClassnameFormat(newVal));
         }
+        /** Changes the contents of an XML tag 'catalogItemId' where the
+         * old text matches oldSymbolicName and optionally oldVersion
+         * to have newSymbolicName and newVersion. 
+         * <p>
+         * This provides a programmatic way to change the catalogItemID. */
+        public Builder changeCatalogItemId(String oldSymbolicName, String oldVersion,
+                String newSymbolicName, String newVersion) {
+            if (oldVersion==null)
+                return changeCatalogItemId(oldSymbolicName, newSymbolicName, newVersion);
+            // warnings use underscore notation because that's what CompoundTransformerLoader uses
+            return xmlReplaceItem("catalogItemId/text()[.='"+
+                Preconditions.checkNotNull(oldSymbolicName, "old_symbolic_name")+":"+Preconditions.checkNotNull(oldVersion, "old_version")+"']", 
+                Preconditions.checkNotNull(newSymbolicName, "new_symbolic_name")+":"+Preconditions.checkNotNull(newVersion, "new_version"));
+        }
+        /** As {@link #changeCatalogItemId(String, String, String, String)} matching any old version. */
+        public Builder changeCatalogItemId(String oldSymbolicName, String newSymbolicName, String newVersion) {
+            return xmlReplaceItem("catalogItemId/text()[starts-with(.,'"+Preconditions.checkNotNull(oldSymbolicName, "old_symbolic_name")+":')]", 
+                Preconditions.checkNotNull(newSymbolicName, "new_symbolic_name")+":"+Preconditions.checkNotNull(newVersion, "new_version"));
+        }
 
         private String toXstreamClassnameFormat(String val) {
             // xstream format for inner classes is like <brooklyn.entity.rebind.transformer.CompoundTransformerTest_-OrigType>

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/7d6c77c6/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoader.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoader.java b/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoader.java
index 9d3cac1..3465709 100644
--- a/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoader.java
+++ b/core/src/main/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoader.java
@@ -62,13 +62,17 @@ public class CompoundTransformerLoader {
             String oldVal = (String) args.get("old_val");
             String newVal = (String) args.get("new_val");
             builder.renameField(clazz, oldVal, newVal);
+        } else if (name.equals("catalogItemId")) {
+            builder.changeCatalogItemId(
+                (String) args.get("old_symbolic_name"), checkString(args.get("old_version"), "old_version"),
+                (String) args.get("new_symbolic_name"), checkString(args.get("new_version"), "new_version"));
         } else if (name.equals("xslt")) {
             String url = (String) args.get("url");
             @SuppressWarnings("unchecked")
             Map<String,?> substitutions = (Map<String, ?>) args.get("substitutions");
             String xsltTemplate = ResourceUtils.create(CompoundTransformer.class).getResourceAsString(url);
             String xslt = TemplateProcessor.processTemplateContents(xsltTemplate, substitutions == null ? ImmutableMap.<String, String>of() : substitutions);
-            // TODO pass XSLT-style parameters instead, maybe?  that's more normal, 
+            // we could pass XSLT-style parameters instead, maybe?  that's more normal, 
             // but OTOH freemarker is maybe more powerful, given our other support there
             builder.xsltTransformer(xslt);
         } else if (name.equals("rawDataTransformer")) {
@@ -83,4 +87,11 @@ public class CompoundTransformerLoader {
             throw new IllegalStateException("Unsupported transform '"+name+"' ("+args+")");
         }
     }
+
+    private static String checkString(Object object, String name) {
+        if (object!=null && !(object instanceof String)) {
+            throw new IllegalArgumentException("Argument '"+name+"' must be a string; numbers may need explicit quoting in YAML.");
+        }
+        return (String) object;
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/7d6c77c6/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoaderTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoaderTest.java b/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoaderTest.java
index 454e860..d55e073 100644
--- a/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoaderTest.java
+++ b/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerLoaderTest.java
@@ -44,6 +44,12 @@ public class CompoundTransformerLoaderTest {
                 "  class_name: myclassname\n"+
                 "  old_val: myoldname\n"+
                 "  new_val: mynewname\n"+
+                // low-level mechanism to change catalogItemId; used (and tested) by higher-level methods
+                // which use symbolic_name:version notation to avoid the unpleasant need for yaml quotes
+                "catalogItemId:\n"+
+                "  old_symbolic_name: myclassname\n"+
+                "  new_symbolic_name: myclassname\n"+
+                "  new_version: '2.0'\n"+
                 "xslt:\n"+
                 "  url: classpath://brooklyn/entity/rebind/transformer/impl/renameType.xslt\n"+
                 "  substitutions:\n"+
@@ -58,7 +64,8 @@ public class CompoundTransformerLoaderTest {
         assertTrue(Iterables.get(rawDataTransformers, 1) instanceof XsltTransformer);
         assertTrue(Iterables.get(rawDataTransformers, 2) instanceof XsltTransformer);
         assertTrue(Iterables.get(rawDataTransformers, 3) instanceof XsltTransformer);
-        assertTrue(Iterables.get(rawDataTransformers, 4) instanceof MyRawDataTransformer);
+        assertTrue(Iterables.get(rawDataTransformers, 4) instanceof XsltTransformer);
+        assertTrue(Iterables.get(rawDataTransformers, 5) instanceof MyRawDataTransformer);
     }
     
     public static class MyRawDataTransformer implements RawDataTransformer {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/7d6c77c6/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java b/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
index 49c1005..db3cbc2 100644
--- a/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
+++ b/core/src/test/java/brooklyn/entity/rebind/transformer/CompoundTransformerTest.java
@@ -294,7 +294,65 @@ public class CompoundTransformerTest extends RebindTestFixtureWithApp {
         
         assertSingleXmlTransformation(transformer, input, expected);
     }
-    
+
+    @Test
+    public void testChangeCatalogItemIdExplicitVersionInXml() throws Exception {
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .changeCatalogItemId("foo", "1.0", "bar", "2.0")
+            .build();
+
+        String input = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <catalogItemId>foo:1.0</catalogItemId>"+NEWLINE+
+                "  <config>ignore</config>"+NEWLINE+
+                "</entity>";
+        String expected = 
+            "<entity myattrib=\"myval\">"+NEWLINE+
+            "  <catalogItemId>bar:2.0</catalogItemId>"+NEWLINE+
+            "  <config>ignore</config>"+NEWLINE+
+            "</entity>";
+        
+        assertSingleXmlTransformation(transformer, input, expected);
+    }
+    @Test
+    public void testChangeCatalogItemIdExplicitVersionNonMatchInXml() throws Exception {
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .changeCatalogItemId("foo", "1.0", "bar", "2.0")
+            .build();
+
+        String input = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <catalogItemId>foo:1.1</catalogItemId>"+NEWLINE+
+                "  <config>ignore</config>"+NEWLINE+
+                "</entity>";
+        String expected = 
+            "<entity myattrib=\"myval\">"+NEWLINE+
+            "  <catalogItemId>foo:1.1</catalogItemId>"+NEWLINE+
+            "  <config>ignore</config>"+NEWLINE+
+            "</entity>";
+        
+        assertSingleXmlTransformation(transformer, input, expected);
+    }
+    @Test
+    public void testChangeCatalogItemIdAnyVersionInXml() throws Exception {
+        CompoundTransformer transformer = CompoundTransformer.builder()
+            .changeCatalogItemId("foo", "bar", "2.0")
+            .build();
+
+        String input = 
+                "<entity myattrib=\"myval\">"+NEWLINE+
+                "  <catalogItemId>foo:1.2</catalogItemId>"+NEWLINE+
+                "  <config>ignore</config>"+NEWLINE+
+                "</entity>";
+        String expected = 
+            "<entity myattrib=\"myval\">"+NEWLINE+
+            "  <catalogItemId>bar:2.0</catalogItemId>"+NEWLINE+
+            "  <config>ignore</config>"+NEWLINE+
+            "</entity>";
+        
+        assertSingleXmlTransformation(transformer, input, expected);
+    }
+
     protected TestApplication transformAndRebind(CompoundTransformer transformer) throws Exception {
         RebindTestUtils.waitForPersisted(origApp);
         BrooklynMementoRawData newRawData = transform(origManagementContext, transformer);


[14/17] incubator-brooklyn git commit: Support scriptDir location config

Posted by an...@apache.org.
Support scriptDir location config

This modifies SshMachineLocation to propagate certain config keys to
flags on SshTool execCommand and execScript invocations; the first use
of this is to propagate the "scriptDir" config. JcloudsLocation is also
modified to propagate this configuration. The result is that "scriptDir"
can be specified in the configuration for a jclouds-based location, and
the value of this property will be passed to every invocation of
SshTool.execScript().

The use case for this is to allow Brooklyn to be usable on locations
where the VM image mounts "/tmp" with "noexec".

Also adds some integration tests to verify the correct operation of the
scriptDir flag.


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

Branch: refs/heads/master
Commit: fc41bb9f516aae2e232a634e8c3524e4649d55a6
Parents: bd9b292
Author: Richard Downer <ri...@apache.org>
Authored: Tue Jan 27 16:06:07 2015 +0000
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:07 2015 +0100

----------------------------------------------------------------------
 .../location/basic/SshMachineLocation.java      | 24 +++++++++++--
 .../SshMachineLocationIntegrationTest.java      | 38 +++++++++++++++++++-
 .../ssh/SshToolAbstractIntegrationTest.java     | 13 +++++++
 .../location/jclouds/JcloudsLocation.java       |  1 +
 4 files changed, 73 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/fc41bb9f/core/src/main/java/brooklyn/location/basic/SshMachineLocation.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/brooklyn/location/basic/SshMachineLocation.java b/core/src/main/java/brooklyn/location/basic/SshMachineLocation.java
index 4a165f2..9482d02 100644
--- a/core/src/main/java/brooklyn/location/basic/SshMachineLocation.java
+++ b/core/src/main/java/brooklyn/location/basic/SshMachineLocation.java
@@ -19,6 +19,8 @@
 package brooklyn.location.basic;
 
 import static brooklyn.util.GroovyJavaMethods.truth;
+
+import com.google.common.annotations.Beta;
 import groovy.lang.Closure;
 
 import java.io.Closeable;
@@ -110,6 +112,7 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
+import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
 import com.google.common.net.HostAndPort;
 
@@ -216,6 +219,14 @@ public class SshMachineLocation extends AbstractLocation implements MachineLocat
                 }
             }));
 
+    /**
+     * The set of config keys on this location which become default values for properties when invoking an SSH
+     * operation.
+     */
+    @Beta
+    public static final Set<ConfigKey<?>> SSH_CONFIG_GIVEN_TO_PROPS = ImmutableSet.<ConfigKey<?>>of(
+            SCRIPT_DIR);
+
     private Task<?> cleanupTask;
     /** callers should use {@link #getSshPoolCache()} */
     @Nullable 
@@ -610,7 +621,7 @@ public class SshMachineLocation extends AbstractLocation implements MachineLocat
         return execCommands(MutableMap.<String,Object>of(), summaryForLogging, commands, env);
     }
     public int execCommands(Map<String,?> props, String summaryForLogging, List<String> commands, Map<String,?> env) {
-        return newExecWithLoggingHelpers().execCommands(props, summaryForLogging, commands, env);
+        return newExecWithLoggingHelpers().execCommands(augmentPropertiesWithSshConfigGivenToProps(props), summaryForLogging, commands, env);
     }
 
     /**
@@ -630,7 +641,16 @@ public class SshMachineLocation extends AbstractLocation implements MachineLocat
         return execScript(MutableMap.<String,Object>of(), summaryForLogging, commands, env);
     }
     public int execScript(Map<String,?> props, String summaryForLogging, List<String> commands, Map<String,?> env) {
-        return newExecWithLoggingHelpers().execScript(props, summaryForLogging, commands, env);
+        return newExecWithLoggingHelpers().execScript(augmentPropertiesWithSshConfigGivenToProps(props), summaryForLogging, commands, env);
+    }
+
+    private Map<String, Object> augmentPropertiesWithSshConfigGivenToProps(Map<String, ?> props) {
+        Map<String,Object> augmentedProps = Maps.newHashMap(props);
+        for (ConfigKey<?> config : SSH_CONFIG_GIVEN_TO_PROPS) {
+            if (!props.containsKey(config.getName()))
+                augmentedProps.put(config.getName(), getConfig(config));
+        }
+        return augmentedProps;
     }
 
     protected ExecWithLoggingHelpers newExecWithLoggingHelpers() {

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/fc41bb9f/core/src/test/java/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/location/basic/SshMachineLocationIntegrationTest.java b/core/src/test/java/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
index 5fbe030..63f5902 100644
--- a/core/src/test/java/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
+++ b/core/src/test/java/brooklyn/location/basic/SshMachineLocationIntegrationTest.java
@@ -21,7 +21,11 @@ package brooklyn.location.basic;
 import java.io.ByteArrayOutputStream;
 import java.security.KeyPair;
 import java.util.Arrays;
+import java.util.Map;
 
+import brooklyn.util.internal.ssh.SshTool;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
 import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.BeforeMethod;
@@ -38,6 +42,8 @@ import brooklyn.util.internal.ssh.sshj.SshjTool.SshjToolBuilder;
 
 import com.google.common.base.Preconditions;
 
+import static org.testng.Assert.assertEquals;
+
 public class SshMachineLocationIntegrationTest {
 
     protected TestApplication app;
@@ -75,7 +81,37 @@ public class SshMachineLocationIntegrationTest {
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         int result = tool.execCommands(MutableMap.<String,Object>of("out", out), Arrays.asList("date"));
         Assert.assertTrue(out.toString().contains(" 20"), "out="+out);
-        Assert.assertEquals(result, 0);
+        assertEquals(result, 0);
+    }
+
+    @Test(groups = "Integration")
+    public void testExecScriptScriptDirFlagIsRespected() throws Exception {
+        // For explanation of (some of) the magic behind this command, see http://stackoverflow.com/a/229606/68898
+        final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi";
+
+        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", true, null).orNull();
+        SshMachineLocation sm = lhp.obtain();
+
+        Map<String, Object> props = ImmutableMap.<String, Object>builder()
+                .put(SshTool.PROP_SCRIPT_DIR.getName(), "/var/tmp")
+                .build();
+        int rc = sm.execScript(props, "Test script directory execution", ImmutableList.of(command));
+        assertEquals(rc, 0);
     }
 
+    @Test(groups = "Integration")
+    public void testLocationScriptDirConfigIsRespected() throws Exception {
+        // For explanation of (some of) the magic behind this command, see http://stackoverflow.com/a/229606/68898
+        final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi";
+
+        Map<String, Object> locationConfig = ImmutableMap.<String, Object>builder()
+                .put(SshMachineLocation.SCRIPT_DIR.getName(), "/var/tmp")
+                .build();
+
+        LocalhostMachineProvisioningLocation lhp = (LocalhostMachineProvisioningLocation) mgmt.getLocationRegistry().resolve("localhost", locationConfig);
+        SshMachineLocation sm = lhp.obtain();
+
+        int rc = sm.execScript("Test script directory execution", ImmutableList.of(command));
+        assertEquals(rc, 0);
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/fc41bb9f/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractIntegrationTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractIntegrationTest.java b/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractIntegrationTest.java
index 1501585..84b1029 100644
--- a/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractIntegrationTest.java
+++ b/core/src/test/java/brooklyn/util/internal/ssh/SshToolAbstractIntegrationTest.java
@@ -285,4 +285,17 @@ public abstract class SshToolAbstractIntegrationTest extends ShellToolAbstractTe
         Assert.assertEquals(CONTENTS.trim(), contents.trim());
     }
 
+    @Test(groups = {"Integration"})
+    public void testScriptDirPropertiesIsRespected() {
+        // For explanation of (some of) the magic behind this command, see http://stackoverflow.com/a/229606/68898
+        final String command = "if [[ \"$0\" == \"/var/tmp/\"* ]]; then true; else false; fi";
+
+        SshTool sshTool = newTool(ImmutableMap.<String, Object>builder()
+                .put(SshTool.PROP_HOST.getName(), "localhost")
+                .build());
+        int rc = sshTool.execScript(ImmutableMap.<String, Object>builder()
+                .put(SshTool.PROP_SCRIPT_DIR.getName(), "/var/tmp")
+                .build(), ImmutableList.of(command));
+        assertEquals(rc, 0);
+    }
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/fc41bb9f/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
----------------------------------------------------------------------
diff --git a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
index b10973d..7abbaca 100644
--- a/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
+++ b/locations/jclouds/src/main/java/brooklyn/location/jclouds/JcloudsLocation.java
@@ -1694,6 +1694,7 @@ public class JcloudsLocation extends AbstractCloudMachineProvisioningLocation im
                     .configureIfNotNull(CLOUD_REGION_ID, nodeRegion)
                     .configure(CALLER_CONTEXT, setup.get(CALLER_CONTEXT))
                     .configure(SshMachineLocation.DETECT_MACHINE_DETAILS, setup.get(SshMachineLocation.DETECT_MACHINE_DETAILS))
+                    .configure(SshMachineLocation.SCRIPT_DIR, setup.get(SshMachineLocation.SCRIPT_DIR))
                     .configureIfNotNull(USE_PORT_FORWARDING, setup.get(USE_PORT_FORWARDING))
                     .configureIfNotNull(PORT_FORWARDER, setup.get(PORT_FORWARDER))
                     .configureIfNotNull(PORT_FORWARDING_MANAGER, setup.get(PORT_FORWARDING_MANAGER)));


[10/17] incubator-brooklyn git commit: fix maven javac purity on JDK7

Posted by an...@apache.org.
fix maven javac purity on JDK7

it also fix javac compiler in intellij


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

Branch: refs/heads/master
Commit: 1f036c6fdf135123ddfb4bc0d5ef73fcc8472330
Parents: 85bdd8d
Author: Andrea Turli <an...@gmail.com>
Authored: Fri Jan 30 10:10:55 2015 +0100
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:07 2015 +0100

----------------------------------------------------------------------
 .../io/brooklyn/camp/spi/AbstractResource.java  | 63 ++++++++++----------
 .../brooklyn/camp/spi/ApplicationComponent.java | 20 +++----
 .../java/io/brooklyn/camp/spi/Assembly.java     | 32 +++++-----
 .../io/brooklyn/camp/spi/AssemblyTemplate.java  | 32 +++++-----
 .../io/brooklyn/camp/spi/PlatformComponent.java | 26 ++++----
 5 files changed, 86 insertions(+), 87 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/1f036c6f/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
index 036a8d6..9906e2b 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
@@ -18,27 +18,26 @@
  */
 package io.brooklyn.camp.spi;
 
-import io.brooklyn.camp.commontypes.RepresentationSkew;
-
 import java.util.Collections;
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
 
-import brooklyn.util.collections.MutableMap;
-import brooklyn.util.text.Identifiers;
-import brooklyn.util.time.Time;
-
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 
+import brooklyn.util.collections.MutableMap;
+import brooklyn.util.text.Identifiers;
+import brooklyn.util.time.Time;
+import io.brooklyn.camp.commontypes.RepresentationSkew;
+
 /** Superclass of CAMP resource implementation objects.
  * Typically used to hold common state of implementation objects
  * and to populate the DTO's used by the REST API.
  * <p>
- * These class instances are typically created using the 
- * static {@link #builder()} methods they contain. 
+ * These class instances are typically created using the
+ * static {@link #builder()} methods they contain.
  * The resulting instances are typically immutable,
  * so where fields can change callers should use a new builder
  * (or update an underlying data store).
@@ -50,7 +49,7 @@ import com.google.common.collect.ImmutableMap;
 public class AbstractResource {
 
     public static final String CAMP_TYPE = "Resource";
-    
+
     private String id = Identifiers.makeRandomId(8);
     private String name;
     private String type;
@@ -59,12 +58,12 @@ public class AbstractResource {
     private Date created = Time.dropMilliseconds(new Date());
     private List<String> tags = Collections.emptyList();
     private RepresentationSkew representationSkew;
-    
+
     private Map<String,Object> customAttributes = new MutableMap<String, Object>();
-    
+
     /** Use {@link #builder()} to create */
     protected AbstractResource() {}
-    
+
     // getters
 
     public String getId() {
@@ -94,66 +93,66 @@ public class AbstractResource {
     public Map<String, Object> getCustomAttributes() {
         return ImmutableMap.copyOf(customAttributes);
     }
-    
+
     // setters
 
-    private void setId(String id) {
+    void setId(String id) {
         this.id = id;
     }
-    private void setName(String name) {
+    void setName(String name) {
         this.name = name;
     }
-    private void setDescription(String description) {
+    void setDescription(String description) {
         this.description = description;
     }
-    private void setSourceCode(String sourceCode) {
+    void setSourceCode(String sourceCode) {
         this.sourceCode = sourceCode;
     }
-    private void setCreated(Date created) {
+    void setCreated(Date created) {
         // precision beyond seconds breaks equals check
         this.created = Time.dropMilliseconds(created);
     }
-    private void setTags(List<String> tags) {
+    void setTags(List<String> tags) {
         this.tags = ImmutableList.copyOf(tags);
     }
-    private void setType(String type) {
+    void setType(String type) {
         this.type = type;
     }
-    private void setRepresentationSkew(RepresentationSkew representationSkew) {
+    void setRepresentationSkew(RepresentationSkew representationSkew) {
         this.representationSkew = representationSkew;
     }
-    public void setCustomAttribute(String key, Object value) {
+    void setCustomAttribute(String key, Object value) {
         this.customAttributes.put(key, value);
     }
-            
+
     // builder
     @SuppressWarnings("rawtypes")
     public static Builder<? extends AbstractResource,? extends Builder> builder() {
         return new AbstractResourceBuilder(CAMP_TYPE);
     }
-    
+
     /** Builder creates the instance up front to avoid repetition of fields in the builder;
      * but prevents object leakage until build and prevents changes after build,
      * so effectively immutable.
      * <p>
      * Similarly setters in the class are private so those objects are also typically effectively immutable. */
     public abstract static class Builder<T extends AbstractResource,U extends Builder<T,U>> {
-        
+
         private boolean built = false;
         private String type = null;
         private T instance = null;
-        
+
         protected Builder(String type) {
             this.type = type;
         }
-        
+
         @SuppressWarnings("unchecked")
         protected T createResource() {
             return (T) new AbstractResource();
         }
-        
+
         protected synchronized T instance() {
-            if (built) 
+            if (built)
                 throw new IllegalStateException("Builder instance from "+this+" cannot be access after build");
             if (instance==null) {
                 instance = createResource();
@@ -165,16 +164,16 @@ public class AbstractResource {
         protected void initialize() {
             if (type!=null) type(type);
         }
-        
+
         public synchronized T build() {
             T result = instance();
             built = true;
             return result;
         }
-        
+
         @SuppressWarnings("unchecked")
         protected U thisBuilder() { return (U)this; }
-        
+
         public U type(String x) { instance().setType(x); return thisBuilder(); }
         public U id(String x) { instance().setId(x); return thisBuilder(); }
         public U name(String x) { instance().setName(x); return thisBuilder(); }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/1f036c6f/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
index 2d70f9c..de1abba 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
@@ -32,14 +32,14 @@ public class ApplicationComponent extends AbstractResource {
 
     public static final String CAMP_TYPE = "ApplicationComponent";
     static { assert CAMP_TYPE.equals(ApplicationComponent.class.getSimpleName()); }
-    
+
     /** Use {@link #builder()} to create */
     protected ApplicationComponent() {}
 
     ResourceLookup<ApplicationComponent> applicationComponents;
     ResourceLookup<PlatformComponent> platformComponents;
     String externalManagementUri;
-    
+
     public ResourceLookup<ApplicationComponent> getApplicationComponents() {
         return applicationComponents != null ? applicationComponents : new EmptyResourceLookup<ApplicationComponent>();
     }
@@ -47,26 +47,26 @@ public class ApplicationComponent extends AbstractResource {
         return platformComponents != null ? platformComponents : new EmptyResourceLookup<PlatformComponent>();
     }
 
-    private void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
+    void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
         this.applicationComponents = applicationComponents;
     }
-    private void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
+    void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
         this.platformComponents = platformComponents;
     }
-    
+
     // builder
-    
+
     public static Builder<? extends ApplicationComponent> builder() {
         return new Builder<ApplicationComponent>(CAMP_TYPE);
     }
-    
+
     public static class Builder<T extends ApplicationComponent> extends AbstractResource.Builder<T,Builder<T>> {
-        
+
         protected Builder(String type) { super(type); }
 
         public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { instance().setApplicationComponents(x); return thisBuilder(); }
         public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { instance().setPlatformComponents(x); return thisBuilder(); }
-        
+
         public synchronized Builder<T> add(ApplicationComponent x) {
             if (instance().applicationComponents==null) {
                 instance().applicationComponents = new BasicResourceLookup<ApplicationComponent>();
@@ -77,7 +77,7 @@ public class ApplicationComponent extends AbstractResource {
             ((BasicResourceLookup<ApplicationComponent>)instance().applicationComponents).add(x);
             return thisBuilder();
         }
-        
+
         public synchronized Builder<T> add(PlatformComponent x) {
             if (instance().platformComponents==null) {
                 instance().platformComponents = new BasicResourceLookup<PlatformComponent>();

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/1f036c6f/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
index 991f704..90511a2 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
@@ -32,18 +32,18 @@ public class Assembly extends AbstractResource {
 
     public static final String CAMP_TYPE = "Assembly";
     static { assert CAMP_TYPE.equals(Assembly.class.getSimpleName()); }
-    
+
     /** Use {@link #builder()} to create */
     protected Assembly() {}
 
     AssemblyTemplate assemblyTemplate;
     ResourceLookup<ApplicationComponent> applicationComponents;
     ResourceLookup<PlatformComponent> platformComponents;
-    
+
     // TODO
 //    "parameterDefinitionUri": URI,
 //    "pdpUri" : URI ?
-                    
+
     public AssemblyTemplate getAssemblyTemplate() {
         return assemblyTemplate;
     }
@@ -53,34 +53,34 @@ public class Assembly extends AbstractResource {
     public ResourceLookup<PlatformComponent> getPlatformComponents() {
         return platformComponents != null ? platformComponents : new EmptyResourceLookup<PlatformComponent>();
     }
-    
-    private void setAssemblyTemplate(AssemblyTemplate assemblyTemplate) {
+
+    void setAssemblyTemplate(AssemblyTemplate assemblyTemplate) {
         this.assemblyTemplate = assemblyTemplate;
     }
-    private void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
+    void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
         this.applicationComponents = applicationComponents;
     }
-    private void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
+    void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
         this.platformComponents = platformComponents;
     }
-    
+
     // builder
-    
+
     public static Builder<? extends Assembly> builder() {
         return new Builder<Assembly>(CAMP_TYPE);
     }
-    
+
     public static class Builder<T extends Assembly> extends AbstractResource.Builder<T,Builder<T>> {
-        
+
         protected Builder(String type) { super(type); }
-        
+
         @SuppressWarnings("unchecked")
         protected T createResource() { return (T) new Assembly(); }
-        
+
         public Builder<T> assemblyTemplate(AssemblyTemplate x) { instance().setAssemblyTemplate(x); return thisBuilder(); }
         public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { instance().setApplicationComponents(x); return thisBuilder(); }
         public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { instance().setPlatformComponents(x); return thisBuilder(); }
-        
+
         public synchronized Builder<T> add(ApplicationComponent x) {
             if (instance().applicationComponents==null) {
                 instance().applicationComponents = new BasicResourceLookup<ApplicationComponent>();
@@ -91,7 +91,7 @@ public class Assembly extends AbstractResource {
             ((BasicResourceLookup<ApplicationComponent>)instance().applicationComponents).add(x);
             return thisBuilder();
         }
-        
+
         public synchronized Builder<T> add(PlatformComponent x) {
             if (instance().platformComponents==null) {
                 instance().platformComponents = new BasicResourceLookup<PlatformComponent>();
@@ -102,7 +102,7 @@ public class Assembly extends AbstractResource {
             ((BasicResourceLookup<PlatformComponent>)instance().platformComponents).add(x);
             return thisBuilder();
         }
-        
+
         @Override
         public synchronized T build() {
             return super.build();

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/1f036c6f/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
index c308b87..6a78a55 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
@@ -35,15 +35,15 @@ public class AssemblyTemplate extends AbstractResource {
 
     public static final String CAMP_TYPE = "AssemblyTemplate";
     static { assert CAMP_TYPE.equals(AssemblyTemplate.class.getSimpleName()); }
-    
+
     Class<? extends AssemblyTemplateInstantiator> instantiator;
     ResourceLookup<ApplicationComponentTemplate> applicationComponentTemplates;
     ResourceLookup<PlatformComponentTemplate> platformComponentTemplates;
-    
+
     // TODO
 //    "parameterDefinitionUri": URI,
 //    "pdpUri" : URI ?
-                    
+
     /** Use {@link #builder()} to create */
     protected AssemblyTemplate() {}
 
@@ -56,30 +56,30 @@ public class AssemblyTemplate extends AbstractResource {
     public ResourceLookup<PlatformComponentTemplate> getPlatformComponentTemplates() {
         return platformComponentTemplates != null ? platformComponentTemplates : new EmptyResourceLookup<PlatformComponentTemplate>();
     }
-    
-    private void setInstantiator(Class<? extends AssemblyTemplateInstantiator> instantiator) {
+
+    void setInstantiator(Class<? extends AssemblyTemplateInstantiator> instantiator) {
         this.instantiator = instantiator;
     }
-    private void setApplicationComponentTemplates(ResourceLookup<ApplicationComponentTemplate> applicationComponentTemplates) {
+    void setApplicationComponentTemplates(ResourceLookup<ApplicationComponentTemplate> applicationComponentTemplates) {
         this.applicationComponentTemplates = applicationComponentTemplates;
     }
-    private void setPlatformComponentTemplates(ResourceLookup<PlatformComponentTemplate> platformComponentTemplates) {
+    void setPlatformComponentTemplates(ResourceLookup<PlatformComponentTemplate> platformComponentTemplates) {
         this.platformComponentTemplates = platformComponentTemplates;
     }
-    
+
     // builder
-    
+
     public static Builder<? extends AssemblyTemplate> builder() {
         return new Builder<AssemblyTemplate>(CAMP_TYPE);
     }
-    
+
     public static class Builder<T extends AssemblyTemplate> extends AbstractResource.Builder<T,Builder<T>> {
-        
+
         protected Builder(String type) { super(type); }
-        
+
         @SuppressWarnings("unchecked")
         protected T createResource() { return (T) new AssemblyTemplate(); }
-        
+
         public Builder<T> instantiator(Class<? extends AssemblyTemplateInstantiator> x) { instance().setInstantiator(x); return thisBuilder(); }
         public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponentTemplate> x) { instance().setApplicationComponentTemplates(x); return thisBuilder(); }
         public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponentTemplate> x) { instance().setPlatformComponentTemplates(x); return thisBuilder(); }
@@ -87,7 +87,7 @@ public class AssemblyTemplate extends AbstractResource {
         /** allows callers to see the partially formed instance when needed, for example to query instantiators;
          *  could be replaced by specific methods as and when that is preferred */
         public T peek() { return instance(); }
-        
+
         public synchronized Builder<T> add(ApplicationComponentTemplate x) {
             if (instance().applicationComponentTemplates==null) {
                 instance().applicationComponentTemplates = new BasicResourceLookup<ApplicationComponentTemplate>();
@@ -98,7 +98,7 @@ public class AssemblyTemplate extends AbstractResource {
             ((BasicResourceLookup<ApplicationComponentTemplate>)instance().applicationComponentTemplates).add(x);
             return thisBuilder();
         }
-        
+
         public synchronized Builder<T> add(PlatformComponentTemplate x) {
             if (instance().platformComponentTemplates==null) {
                 instance().platformComponentTemplates = new BasicResourceLookup<PlatformComponentTemplate>();
@@ -109,7 +109,7 @@ public class AssemblyTemplate extends AbstractResource {
             ((BasicResourceLookup<PlatformComponentTemplate>)instance().platformComponentTemplates).add(x);
             return thisBuilder();
         }
-        
+
         @Override
         public synchronized T build() {
             Preconditions.checkNotNull(instance().instantiator);

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/1f036c6f/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
index 3e3363b..a5c343a 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
@@ -32,14 +32,14 @@ public class PlatformComponent extends AbstractResource {
 
     public static final String CAMP_TYPE = "PlatformComponent";
     static { assert CAMP_TYPE.equals(PlatformComponent.class.getSimpleName()); }
-    
+
     /** Use {@link #builder()} to create */
     protected PlatformComponent() {}
 
     ResourceLookup<ApplicationComponent> applicationComponents;
     ResourceLookup<PlatformComponent> platformComponents;
     String externalManagementUri;
-    
+
     public ResourceLookup<ApplicationComponent> getApplicationComponents() {
         return applicationComponents != null ? applicationComponents : new EmptyResourceLookup<ApplicationComponent>();
     }
@@ -47,34 +47,34 @@ public class PlatformComponent extends AbstractResource {
         return platformComponents != null ? platformComponents : new EmptyResourceLookup<PlatformComponent>();
     }
 
-    private void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
+    void setApplicationComponents(ResourceLookup<ApplicationComponent> applicationComponents) {
         this.applicationComponents = applicationComponents;
     }
-    private void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
+    void setPlatformComponents(ResourceLookup<PlatformComponent> platformComponents) {
         this.platformComponents = platformComponents;
     }
-    
+
     public String getExternalManagementUri() {
         return externalManagementUri;
     }
-    private void setExternalManagementUri(String externalManagementUri) {
+    void setExternalManagementUri(String externalManagementUri) {
         this.externalManagementUri = externalManagementUri;
     }
-    
+
     // builder
-    
+
     public static Builder<? extends PlatformComponent> builder() {
         return new Builder<PlatformComponent>(CAMP_TYPE);
     }
-    
+
     public static class Builder<T extends PlatformComponent> extends AbstractResource.Builder<T,Builder<T>> {
-        
+
         protected Builder(String type) { super(type); }
-        
+
         public Builder<T> externalManagementUri(String x) { instance().setExternalManagementUri(x); return thisBuilder(); }
         public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { instance().setApplicationComponents(x); return thisBuilder(); }
         public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { instance().setPlatformComponents(x); return thisBuilder(); }
-        
+
         public synchronized Builder<T> add(ApplicationComponent x) {
             if (instance().applicationComponents==null) {
                 instance().applicationComponents = new BasicResourceLookup<ApplicationComponent>();
@@ -85,7 +85,7 @@ public class PlatformComponent extends AbstractResource {
             ((BasicResourceLookup<ApplicationComponent>)instance().applicationComponents).add(x);
             return thisBuilder();
         }
-        
+
         public synchronized Builder<T> add(PlatformComponent x) {
             if (instance().platformComponents==null) {
                 instance().platformComponents = new BasicResourceLookup<PlatformComponent>();


[08/17] incubator-brooklyn git commit: changes to the camp builder to support pure-javac 1.7 compilation

Posted by an...@apache.org.
changes to the camp builder to support pure-javac 1.7 compilation

the root cause was (from http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html):

> Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.


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

Branch: refs/heads/master
Commit: 8f55a6e3fcbf9395efefb935dae4a6ccedf6c6fb
Parents: efdb672
Author: Alex Heneveld <al...@cloudsoftcorp.com>
Authored: Thu Jan 29 13:16:46 2015 +0000
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:07 2015 +0100

----------------------------------------------------------------------
 .../io/brooklyn/camp/spi/AbstractResource.java  | 47 +++++++++-----------
 .../brooklyn/camp/spi/ApplicationComponent.java | 31 ++++++-------
 .../camp/spi/ApplicationComponentTemplate.java  |  7 +--
 .../java/io/brooklyn/camp/spi/Assembly.java     | 33 +++++++-------
 .../io/brooklyn/camp/spi/AssemblyTemplate.java  | 38 ++++++++--------
 .../io/brooklyn/camp/spi/PlatformComponent.java | 33 +++++++-------
 .../camp/spi/PlatformComponentTemplate.java     |  7 +--
 .../brooklyn/camp/spi/PlatformRootSummary.java  |  7 +--
 8 files changed, 89 insertions(+), 114 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/8f55a6e3/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
index 036a8d6..5f04e20 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AbstractResource.java
@@ -129,7 +129,7 @@ public class AbstractResource {
     // builder
     @SuppressWarnings("rawtypes")
     public static Builder<? extends AbstractResource,? extends Builder> builder() {
-        return new AbstractResourceBuilder(CAMP_TYPE);
+        return new AbstractResource().new AbstractResourceBuilder(CAMP_TYPE);
     }
     
     /** Builder creates the instance up front to avoid repetition of fields in the builder;
@@ -137,59 +137,54 @@ public class AbstractResource {
      * so effectively immutable.
      * <p>
      * Similarly setters in the class are private so those objects are also typically effectively immutable. */
-    public abstract static class Builder<T extends AbstractResource,U extends Builder<T,U>> {
+    public abstract class Builder<T extends AbstractResource,U extends Builder<T,U>> {
         
         private boolean built = false;
         private String type = null;
-        private T instance = null;
+        private boolean initialized = false;
         
         protected Builder(String type) {
             this.type = type;
         }
         
-        @SuppressWarnings("unchecked")
-        protected T createResource() {
-            return (T) new AbstractResource();
-        }
-        
-        protected synchronized T instance() {
+        protected final synchronized void check() {
             if (built) 
                 throw new IllegalStateException("Builder instance from "+this+" cannot be access after build");
-            if (instance==null) {
-                instance = createResource();
+            if (!initialized) {
+                initialized = true;
                 initialize();
             }
-            return instance;
         }
 
         protected void initialize() {
             if (type!=null) type(type);
         }
-        
+
+        @SuppressWarnings("unchecked")
         public synchronized T build() {
-            T result = instance();
+            check();
             built = true;
-            return result;
+            return (T) AbstractResource.this;
         }
         
         @SuppressWarnings("unchecked")
         protected U thisBuilder() { return (U)this; }
         
-        public U type(String x) { instance().setType(x); return thisBuilder(); }
-        public U id(String x) { instance().setId(x); return thisBuilder(); }
-        public U name(String x) { instance().setName(x); return thisBuilder(); }
-        public U description(String x) { instance().setDescription(x); return thisBuilder(); }
-        public U created(Date x) { instance().setCreated(x); return thisBuilder(); }
-        public U tags(List<String> x) { instance().setTags(x); return thisBuilder(); }
-        public U representationSkew(RepresentationSkew x) { instance().setRepresentationSkew(x); return thisBuilder(); }
-        public U customAttribute(String key, Object value) { instance().setCustomAttribute(key, value); return thisBuilder(); }
-        public U sourceCode(String x) { instance().setSourceCode(x); return thisBuilder(); }
+        public U type(String x) { check(); AbstractResource.this.setType(x); return thisBuilder(); }
+        public U id(String x) { check(); AbstractResource.this.setId(x); return thisBuilder(); }
+        public U name(String x) { check(); AbstractResource.this.setName(x); return thisBuilder(); }
+        public U description(String x) { check(); AbstractResource.this.setDescription(x); return thisBuilder(); }
+        public U created(Date x) { check(); AbstractResource.this.setCreated(x); return thisBuilder(); }
+        public U tags(List<String> x) { check(); AbstractResource.this.setTags(x); return thisBuilder(); }
+        public U representationSkew(RepresentationSkew x) { check(); AbstractResource.this.setRepresentationSkew(x); return thisBuilder(); }
+        public U customAttribute(String key, Object value) { check(); AbstractResource.this.setCustomAttribute(key, value); return thisBuilder(); }
+        public U sourceCode(String x) { check(); AbstractResource.this.setSourceCode(x); return thisBuilder(); }
 
 //        public String type() { return instance().type; }
     }
-
+    
     @VisibleForTesting
-    protected static class AbstractResourceBuilder extends Builder<AbstractResource,AbstractResourceBuilder> {
+    protected class AbstractResourceBuilder extends Builder<AbstractResource,AbstractResourceBuilder> {
         protected AbstractResourceBuilder(String type) {
             super(type);
         }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/8f55a6e3/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
index 2d70f9c..3e956a4 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponent.java
@@ -57,40 +57,37 @@ public class ApplicationComponent extends AbstractResource {
     // builder
     
     public static Builder<? extends ApplicationComponent> builder() {
-        return new Builder<ApplicationComponent>(CAMP_TYPE);
+        return new ApplicationComponent().new Builder<ApplicationComponent>(CAMP_TYPE);
     }
     
-    public static class Builder<T extends ApplicationComponent> extends AbstractResource.Builder<T,Builder<T>> {
+    public class Builder<T extends ApplicationComponent> extends AbstractResource.Builder<T,Builder<T>> {
         
         protected Builder(String type) { super(type); }
 
-        public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { instance().setApplicationComponents(x); return thisBuilder(); }
-        public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { instance().setPlatformComponents(x); return thisBuilder(); }
+        public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { ApplicationComponent.this.setApplicationComponents(x); return thisBuilder(); }
+        public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { ApplicationComponent.this.setPlatformComponents(x); return thisBuilder(); }
         
         public synchronized Builder<T> add(ApplicationComponent x) {
-            if (instance().applicationComponents==null) {
-                instance().applicationComponents = new BasicResourceLookup<ApplicationComponent>();
+            if (ApplicationComponent.this.applicationComponents==null) {
+                ApplicationComponent.this.applicationComponents = new BasicResourceLookup<ApplicationComponent>();
             }
-            if (!(instance().applicationComponents instanceof BasicResourceLookup)) {
-                throw new IllegalStateException("Cannot add to resource lookup "+instance().applicationComponents);
+            if (!(ApplicationComponent.this.applicationComponents instanceof BasicResourceLookup)) {
+                throw new IllegalStateException("Cannot add to resource lookup "+ApplicationComponent.this.applicationComponents);
             }
-            ((BasicResourceLookup<ApplicationComponent>)instance().applicationComponents).add(x);
+            ((BasicResourceLookup<ApplicationComponent>)ApplicationComponent.this.applicationComponents).add(x);
             return thisBuilder();
         }
         
         public synchronized Builder<T> add(PlatformComponent x) {
-            if (instance().platformComponents==null) {
-                instance().platformComponents = new BasicResourceLookup<PlatformComponent>();
+            if (ApplicationComponent.this.platformComponents==null) {
+                ApplicationComponent.this.platformComponents = new BasicResourceLookup<PlatformComponent>();
             }
-            if (!(instance().platformComponents instanceof BasicResourceLookup)) {
-                throw new IllegalStateException("Cannot add to resource lookup "+instance().platformComponents);
+            if (!(ApplicationComponent.this.platformComponents instanceof BasicResourceLookup)) {
+                throw new IllegalStateException("Cannot add to resource lookup "+ApplicationComponent.this.platformComponents);
             }
-            ((BasicResourceLookup<PlatformComponent>)instance().platformComponents).add(x);
+            ((BasicResourceLookup<PlatformComponent>)ApplicationComponent.this.platformComponents).add(x);
             return thisBuilder();
         }
-
-        @SuppressWarnings("unchecked")
-        protected T createResource() { return (T) new ApplicationComponent(); }
     }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/8f55a6e3/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponentTemplate.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponentTemplate.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponentTemplate.java
index 34d03f4..f3212c7 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponentTemplate.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/ApplicationComponentTemplate.java
@@ -41,16 +41,13 @@ public class ApplicationComponentTemplate extends AbstractResource {
     // builder
     
     public static Builder<? extends ApplicationComponentTemplate> builder() {
-        return new Builder<ApplicationComponentTemplate>(CAMP_TYPE);
+        return new ApplicationComponentTemplate().new Builder<ApplicationComponentTemplate>(CAMP_TYPE);
     }
     
-    public static class Builder<T extends ApplicationComponentTemplate> extends AbstractResource.Builder<T,Builder<T>> {
+    public class Builder<T extends ApplicationComponentTemplate> extends AbstractResource.Builder<T,Builder<T>> {
         
         protected Builder(String type) { super(type); }
         
-        @SuppressWarnings("unchecked")
-        protected T createResource() { return (T) new ApplicationComponentTemplate(); }
-        
 //        public Builder<T> foo(String x) { instance().setFoo(x); return thisBuilder(); }
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/8f55a6e3/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
index 991f704..15cfd51 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/Assembly.java
@@ -67,39 +67,36 @@ public class Assembly extends AbstractResource {
     // builder
     
     public static Builder<? extends Assembly> builder() {
-        return new Builder<Assembly>(CAMP_TYPE);
+        return new Assembly().new Builder<Assembly>(CAMP_TYPE);
     }
     
-    public static class Builder<T extends Assembly> extends AbstractResource.Builder<T,Builder<T>> {
+    public class Builder<T extends Assembly> extends AbstractResource.Builder<T,Builder<T>> {
         
         protected Builder(String type) { super(type); }
         
-        @SuppressWarnings("unchecked")
-        protected T createResource() { return (T) new Assembly(); }
-        
-        public Builder<T> assemblyTemplate(AssemblyTemplate x) { instance().setAssemblyTemplate(x); return thisBuilder(); }
-        public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { instance().setApplicationComponents(x); return thisBuilder(); }
-        public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { instance().setPlatformComponents(x); return thisBuilder(); }
+        public Builder<T> assemblyTemplate(AssemblyTemplate x) { Assembly.this.setAssemblyTemplate(x); return thisBuilder(); }
+        public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { Assembly.this.setApplicationComponents(x); return thisBuilder(); }
+        public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { Assembly.this.setPlatformComponents(x); return thisBuilder(); }
         
         public synchronized Builder<T> add(ApplicationComponent x) {
-            if (instance().applicationComponents==null) {
-                instance().applicationComponents = new BasicResourceLookup<ApplicationComponent>();
+            if (Assembly.this.applicationComponents==null) {
+                Assembly.this.applicationComponents = new BasicResourceLookup<ApplicationComponent>();
             }
-            if (!(instance().applicationComponents instanceof BasicResourceLookup)) {
-                throw new IllegalStateException("Cannot add to resource lookup "+instance().applicationComponents);
+            if (!(Assembly.this.applicationComponents instanceof BasicResourceLookup)) {
+                throw new IllegalStateException("Cannot add to resource lookup "+Assembly.this.applicationComponents);
             }
-            ((BasicResourceLookup<ApplicationComponent>)instance().applicationComponents).add(x);
+            ((BasicResourceLookup<ApplicationComponent>)Assembly.this.applicationComponents).add(x);
             return thisBuilder();
         }
         
         public synchronized Builder<T> add(PlatformComponent x) {
-            if (instance().platformComponents==null) {
-                instance().platformComponents = new BasicResourceLookup<PlatformComponent>();
+            if (Assembly.this.platformComponents==null) {
+                Assembly.this.platformComponents = new BasicResourceLookup<PlatformComponent>();
             }
-            if (!(instance().platformComponents instanceof BasicResourceLookup)) {
-                throw new IllegalStateException("Cannot add to resource lookup "+instance().platformComponents);
+            if (!(Assembly.this.platformComponents instanceof BasicResourceLookup)) {
+                throw new IllegalStateException("Cannot add to resource lookup "+Assembly.this.platformComponents);
             }
-            ((BasicResourceLookup<PlatformComponent>)instance().platformComponents).add(x);
+            ((BasicResourceLookup<PlatformComponent>)Assembly.this.platformComponents).add(x);
             return thisBuilder();
         }
         

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/8f55a6e3/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
index c308b87..4779a1c 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/AssemblyTemplate.java
@@ -70,49 +70,47 @@ public class AssemblyTemplate extends AbstractResource {
     // builder
     
     public static Builder<? extends AssemblyTemplate> builder() {
-        return new Builder<AssemblyTemplate>(CAMP_TYPE);
+        return new AssemblyTemplate().new Builder<AssemblyTemplate>(CAMP_TYPE);
     }
     
-    public static class Builder<T extends AssemblyTemplate> extends AbstractResource.Builder<T,Builder<T>> {
+    public class Builder<T extends AssemblyTemplate> extends AbstractResource.Builder<T,Builder<T>> {
         
         protected Builder(String type) { super(type); }
         
-        @SuppressWarnings("unchecked")
-        protected T createResource() { return (T) new AssemblyTemplate(); }
-        
-        public Builder<T> instantiator(Class<? extends AssemblyTemplateInstantiator> x) { instance().setInstantiator(x); return thisBuilder(); }
-        public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponentTemplate> x) { instance().setApplicationComponentTemplates(x); return thisBuilder(); }
-        public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponentTemplate> x) { instance().setPlatformComponentTemplates(x); return thisBuilder(); }
+        public Builder<T> instantiator(Class<? extends AssemblyTemplateInstantiator> x) { AssemblyTemplate.this.setInstantiator(x); return thisBuilder(); }
+        public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponentTemplate> x) { AssemblyTemplate.this.setApplicationComponentTemplates(x); return thisBuilder(); }
+        public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponentTemplate> x) { AssemblyTemplate.this.setPlatformComponentTemplates(x); return thisBuilder(); }
 
         /** allows callers to see the partially formed instance when needed, for example to query instantiators;
          *  could be replaced by specific methods as and when that is preferred */
-        public T peek() { return instance(); }
+        @SuppressWarnings("unchecked")
+        public T peek() { return (T) AssemblyTemplate.this; }
         
         public synchronized Builder<T> add(ApplicationComponentTemplate x) {
-            if (instance().applicationComponentTemplates==null) {
-                instance().applicationComponentTemplates = new BasicResourceLookup<ApplicationComponentTemplate>();
+            if (AssemblyTemplate.this.applicationComponentTemplates==null) {
+                AssemblyTemplate.this.applicationComponentTemplates = new BasicResourceLookup<ApplicationComponentTemplate>();
             }
-            if (!(instance().applicationComponentTemplates instanceof BasicResourceLookup)) {
-                throw new IllegalStateException("Cannot add to resource lookup "+instance().applicationComponentTemplates);
+            if (!(AssemblyTemplate.this.applicationComponentTemplates instanceof BasicResourceLookup)) {
+                throw new IllegalStateException("Cannot add to resource lookup "+AssemblyTemplate.this.applicationComponentTemplates);
             }
-            ((BasicResourceLookup<ApplicationComponentTemplate>)instance().applicationComponentTemplates).add(x);
+            ((BasicResourceLookup<ApplicationComponentTemplate>)AssemblyTemplate.this.applicationComponentTemplates).add(x);
             return thisBuilder();
         }
         
         public synchronized Builder<T> add(PlatformComponentTemplate x) {
-            if (instance().platformComponentTemplates==null) {
-                instance().platformComponentTemplates = new BasicResourceLookup<PlatformComponentTemplate>();
+            if (AssemblyTemplate.this.platformComponentTemplates==null) {
+                AssemblyTemplate.this.platformComponentTemplates = new BasicResourceLookup<PlatformComponentTemplate>();
             }
-            if (!(instance().platformComponentTemplates instanceof BasicResourceLookup)) {
-                throw new IllegalStateException("Cannot add to resource lookup "+instance().platformComponentTemplates);
+            if (!(AssemblyTemplate.this.platformComponentTemplates instanceof BasicResourceLookup)) {
+                throw new IllegalStateException("Cannot add to resource lookup "+AssemblyTemplate.this.platformComponentTemplates);
             }
-            ((BasicResourceLookup<PlatformComponentTemplate>)instance().platformComponentTemplates).add(x);
+            ((BasicResourceLookup<PlatformComponentTemplate>)AssemblyTemplate.this.platformComponentTemplates).add(x);
             return thisBuilder();
         }
         
         @Override
         public synchronized T build() {
-            Preconditions.checkNotNull(instance().instantiator);
+            Preconditions.checkNotNull(AssemblyTemplate.this.instantiator);
             return super.build();
         }
     }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/8f55a6e3/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
index 3e3363b..d531174 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponent.java
@@ -64,41 +64,38 @@ public class PlatformComponent extends AbstractResource {
     // builder
     
     public static Builder<? extends PlatformComponent> builder() {
-        return new Builder<PlatformComponent>(CAMP_TYPE);
+        return new PlatformComponent().new Builder<PlatformComponent>(CAMP_TYPE);
     }
     
-    public static class Builder<T extends PlatformComponent> extends AbstractResource.Builder<T,Builder<T>> {
+    public class Builder<T extends PlatformComponent> extends AbstractResource.Builder<T,Builder<T>> {
         
         protected Builder(String type) { super(type); }
         
-        public Builder<T> externalManagementUri(String x) { instance().setExternalManagementUri(x); return thisBuilder(); }
-        public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { instance().setApplicationComponents(x); return thisBuilder(); }
-        public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { instance().setPlatformComponents(x); return thisBuilder(); }
+        public Builder<T> externalManagementUri(String x) { PlatformComponent.this.setExternalManagementUri(x); return thisBuilder(); }
+        public Builder<T> applicationComponentTemplates(ResourceLookup<ApplicationComponent> x) { PlatformComponent.this.setApplicationComponents(x); return thisBuilder(); }
+        public Builder<T> platformComponentTemplates(ResourceLookup<PlatformComponent> x) { PlatformComponent.this.setPlatformComponents(x); return thisBuilder(); }
         
         public synchronized Builder<T> add(ApplicationComponent x) {
-            if (instance().applicationComponents==null) {
-                instance().applicationComponents = new BasicResourceLookup<ApplicationComponent>();
+            if (PlatformComponent.this.applicationComponents==null) {
+                PlatformComponent.this.applicationComponents = new BasicResourceLookup<ApplicationComponent>();
             }
-            if (!(instance().applicationComponents instanceof BasicResourceLookup)) {
-                throw new IllegalStateException("Cannot add to resource lookup "+instance().applicationComponents);
+            if (!(PlatformComponent.this.applicationComponents instanceof BasicResourceLookup)) {
+                throw new IllegalStateException("Cannot add to resource lookup "+PlatformComponent.this.applicationComponents);
             }
-            ((BasicResourceLookup<ApplicationComponent>)instance().applicationComponents).add(x);
+            ((BasicResourceLookup<ApplicationComponent>)PlatformComponent.this.applicationComponents).add(x);
             return thisBuilder();
         }
         
         public synchronized Builder<T> add(PlatformComponent x) {
-            if (instance().platformComponents==null) {
-                instance().platformComponents = new BasicResourceLookup<PlatformComponent>();
+            if (PlatformComponent.this.platformComponents==null) {
+                PlatformComponent.this.platformComponents = new BasicResourceLookup<PlatformComponent>();
             }
-            if (!(instance().platformComponents instanceof BasicResourceLookup)) {
-                throw new IllegalStateException("Cannot add to resource lookup "+instance().platformComponents);
+            if (!(PlatformComponent.this.platformComponents instanceof BasicResourceLookup)) {
+                throw new IllegalStateException("Cannot add to resource lookup "+PlatformComponent.this.platformComponents);
             }
-            ((BasicResourceLookup<PlatformComponent>)instance().platformComponents).add(x);
+            ((BasicResourceLookup<PlatformComponent>)PlatformComponent.this.platformComponents).add(x);
             return thisBuilder();
         }
-
-        @SuppressWarnings("unchecked")
-        protected T createResource() { return (T) new PlatformComponent(); }
     }
 
 }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/8f55a6e3/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponentTemplate.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponentTemplate.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponentTemplate.java
index 8cedcb4..7f93f34 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponentTemplate.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformComponentTemplate.java
@@ -39,16 +39,13 @@ public class PlatformComponentTemplate extends AbstractResource {
     // builder
     
     public static Builder<? extends PlatformComponentTemplate> builder() {
-        return new Builder<PlatformComponentTemplate>(CAMP_TYPE);
+        return new PlatformComponentTemplate().new Builder<PlatformComponentTemplate>(CAMP_TYPE);
     }
     
-    public static class Builder<T extends PlatformComponentTemplate> extends AbstractResource.Builder<T,Builder<T>> {
+    public class Builder<T extends PlatformComponentTemplate> extends AbstractResource.Builder<T,Builder<T>> {
         
         protected Builder(String type) { super(type); }
         
-        @SuppressWarnings("unchecked")
-        protected T createResource() { return (T) new PlatformComponentTemplate(); }
-        
 //        public Builder<T> foo(String x) { instance().setFoo(x); return thisBuilder(); }
     }
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/8f55a6e3/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformRootSummary.java
----------------------------------------------------------------------
diff --git a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformRootSummary.java b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformRootSummary.java
index ca6b433..eb34ff9 100644
--- a/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformRootSummary.java
+++ b/camp/camp-base/src/main/java/io/brooklyn/camp/spi/PlatformRootSummary.java
@@ -53,16 +53,13 @@ public class PlatformRootSummary extends AbstractResource {
     // builder
     
     public static Builder<? extends PlatformRootSummary> builder() {
-        return new Builder<PlatformRootSummary>(CAMP_TYPE);
+        return new PlatformRootSummary().new Builder<PlatformRootSummary>(CAMP_TYPE);
     }
     
-    public static class Builder<T extends PlatformRootSummary> extends AbstractResource.Builder<T,Builder<T>> {
+    public class Builder<T extends PlatformRootSummary> extends AbstractResource.Builder<T,Builder<T>> {
         
         protected Builder(String type) { super(type); }
         
-        @SuppressWarnings("unchecked")
-        protected T createResource() { return (T) new PlatformRootSummary(); }
-        
         protected void initialize() {
             super.initialize();
             // TODO a better way not to have an ID here (new subclass BasicIdentifiableResource for other BasicResource instances)


[07/17] incubator-brooklyn git commit: nginx support for upstream https, disable SSLv3

Posted by an...@apache.org.
nginx support for upstream https, disable SSLv3

Make the template config closer to the NginxDefaultConfigGenerator, support non-domain config.


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

Branch: refs/heads/master
Commit: 80429aaa1dd22fdc9ebb083804d6ed60b9fa9f9b
Parents: b08572f
Author: Svetoslav Neykov <sv...@cloudsoftcorp.com>
Authored: Tue Jan 27 21:58:44 2015 +0200
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:06 2015 +0100

----------------------------------------------------------------------
 .../entity/proxy/nginx/NginxDefaultConfigGenerator.java        | 2 ++
 .../entity/proxy/nginx/NginxTemplateConfigGenerator.java       | 3 +--
 .../src/main/resources/brooklyn/entity/proxy/nginx/server.conf | 6 +++++-
 3 files changed, 8 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80429aaa/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxDefaultConfigGenerator.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxDefaultConfigGenerator.java b/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxDefaultConfigGenerator.java
index 7ba069e..1ed7e49 100644
--- a/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxDefaultConfigGenerator.java
+++ b/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxDefaultConfigGenerator.java
@@ -249,6 +249,8 @@ public class NginxDefaultConfigGenerator implements NginxConfigFileGenerator {
                 out.append(prefix);
                 out.append("ssl_certificate_key " + key + ";\n");
             }
+
+            out.append("ssl_protocols TLSv1 TLSv1.1 TLSv1.2;\n");
         }
         return true;
     }

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80429aaa/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxTemplateConfigGenerator.java
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxTemplateConfigGenerator.java b/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxTemplateConfigGenerator.java
index d141ecf..faab7a9 100644
--- a/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxTemplateConfigGenerator.java
+++ b/software/webapp/src/main/java/brooklyn/entity/proxy/nginx/NginxTemplateConfigGenerator.java
@@ -26,7 +26,6 @@ import brooklyn.entity.basic.ConfigKeys;
 import brooklyn.entity.proxy.ProxySslConfig;
 import brooklyn.util.ResourceUtils;
 import brooklyn.util.collections.MutableMap;
-import brooklyn.util.flags.SetFromFlag;
 import brooklyn.util.text.Strings;
 import brooklyn.util.text.TemplateProcessor;
 
@@ -39,7 +38,7 @@ import com.google.common.collect.Multimap;
 public class NginxTemplateConfigGenerator implements NginxConfigFileGenerator {
 
     public static final ConfigKey<String> SERVER_CONF_TEMPLATE_URL = ConfigKeys.newStringConfigKey(
-            "nginx.config.templateUrl", "The server.conf configuration file URL (FreeMarker template)");
+            "nginx.config.templateUrl", "The server.conf configuration file URL (FreeMarker template)", "classpath://brooklyn/entity/proxy/nginx/server.conf");
 
     public NginxTemplateConfigGenerator() { }
 

http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/80429aaa/software/webapp/src/main/resources/brooklyn/entity/proxy/nginx/server.conf
----------------------------------------------------------------------
diff --git a/software/webapp/src/main/resources/brooklyn/entity/proxy/nginx/server.conf b/software/webapp/src/main/resources/brooklyn/entity/proxy/nginx/server.conf
index 72f38e6..eb34ddb 100644
--- a/software/webapp/src/main/resources/brooklyn/entity/proxy/nginx/server.conf
+++ b/software/webapp/src/main/resources/brooklyn/entity/proxy/nginx/server.conf
@@ -41,13 +41,16 @@ http {
     default_type                    application/octet-stream;
 
     server {
+        [#if entity.domain?has_content]
         server_name                 ${entity.domain};
+        [/#if]
 
         [#if entity.ssl]
         # HTTPS setup
         listen                      ${entity.port?c} default ssl;
         ssl_certificate             ${driver.runDir}/conf/global.crt;
         ssl_certificate_key         ${driver.runDir}/conf/global.key;
+        ssl_protocols               TLSv1 TLSv1.1 TLSv1.2;
         [#else]
         # HTTP setup
         listen                      ${entity.port?c};
@@ -60,7 +63,8 @@ http {
 
         [#if entity.serverPoolAddresses?has_content]
         location / {
-            proxy_pass              http://${entity.id};
+            server_tokens off;
+            proxy_pass              http[#if entity.portNumberSensor.name == "https.port"]s[/#if]://${entity.id};
             proxy_set_header        X-Real-IP [#noparse]$remote_addr[/#noparse];
             proxy_set_header        X-Forwarded-For [#noparse]$proxy_add_x_forwarded_for[/#noparse];
             proxy_set_header        Host [#noparse]$http_host[/#noparse];


[11/17] incubator-brooklyn git commit: Fix projects build order

Posted by an...@apache.org.
Fix projects build order

The quickstart generated project depends on downstream-parent, but it is not yet built. Change modules build order.


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

Branch: refs/heads/master
Commit: 8e9d98a1c0681ad39ab94bae1f3295e7a03f3aa3
Parents: 1f036c6
Author: Svetoslav Neykov <sv...@cloudsoftcorp.com>
Authored: Fri Jan 30 13:39:08 2015 +0200
Committer: Andrea Turli <an...@gmail.com>
Committed: Tue Feb 3 11:25:07 2015 +0100

----------------------------------------------------------------------
 pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-brooklyn/blob/8e9d98a1/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 9f4d9df..a1dd7eb 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1296,8 +1296,8 @@
                 <module>usage/cli</module>
                 <module>usage/all</module>
                 <module>usage/dist</module>
-                <module>usage/archetypes/quickstart</module>
                 <module>usage/downstream-parent</module>
+                <module>usage/archetypes/quickstart</module>
             </modules>
         </profile>
         <profile>